【发布时间】:2016-05-27 22:23:40
【问题描述】:
当我为这样的结构分配内存时:
typedef struct _My_struct {
int myInt;
} My_struct;
My_struct* tmp = (My_struct*)malloc(sizeof(My_struct));
然后我尝试在其中设置一些值,如下所示:
tmp->myInt = 0;
我的程序崩溃了。 在调试模式下运行时,我看到 tmp 中的所有值都是 NULL,因此它可能由于 NullPointerException 而崩溃。 为什么我不能正确分配内存?
【问题讨论】:
-
我刚刚使用这个测试运行了你的代码:
#include <stdlib.h> #include <stdio.h> typedef struct _My_struct { int myInt; } My_struct; int main(void) { My_struct* tmp = malloc(sizeof(My_struct)); tmp->myInt = 1424838; printf("%d\n", tmp->myInt); return 0; }。看起来不错,没有编译器警告,运行正常。所以错误必须在您的代码中的其他地方。顺便说一句,不要将malloc()结果转换为 C。 -
不需要对生成的 malloc 调用进行类型转换。