我在尝试在C中动态分配结构时遇到问题:
typedef struct
{
uint8_t wifiSSID[30];
uint8_t wifiPassword[20];
}
tWifiPair;
typedef struct
{
tWifiPair *wifiNetworks; // this needs to become an array with 2 elements
// if I do the above like this tWifiPair wifiNetworks[1] - all works fine
}
tEEPROMSettings;
tEEPROMSettings gEEPROMSettings;
int main()
{
gEEPROMSettings.wifiNetworks = (tWifiPair *)calloc(2, sizeof(tWifiPair));
// .... writing to gEEPROMSettings.wifiNetworks[0].wifiSSID crashes the program, unfortunately I can't see the error, but the compiler doesn't throw any errors/warnings
}
如果此tWifiPair * wifiNetworks是静态完成的-tWifiPair wifiNetworks [1]-可以正常工作,但我需要动态执行此操作,并且可能在程序运行时进行更改。
它在嵌入式平台-ARM tm4c1294ncpdt上运行,编译器为CCS6。
您能指出我的错误所在吗?谢谢!
您需要检查的返回值calloc
以确保成功。
成功时,将指向该函数分配的内存块的指针。该指针的类型始终为void *,可以将其强制转换为所需的数据指针类型,以便将其取消引用。如果函数未能分配所请求的内存块,则返回空指针。
从这个参考
现在,如果calloc
失败了,那就是另一个问题。
更新评论中的信息以供其他阅读:
这似乎是一个嵌入式系统,可能配置了一个小的堆。calloc
确实会返回NULL
,因此分配失败。根据您的编译器/链接器,您可能需要调整链接器脚本,分散文件或项目选项以更改堆大小。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句