本例中使用 Malloc 或 Calloc 分配内存有什么区别?
使用 Calloc 会导致内存损坏,但使用 Malloc 就可以了!
我的示例类似于(但具有许多值):
如果代码错误,该怎么办?
typedef struct {
int ID, age;
} person;
typedef struct {
person *person;
struct NO *next;
} NO;
... // with calloc, the memory breaks
// with (NO*)malloc(sizeof(NO)) it´s fine
NO *p1, *px1, *px2;
px2 = (NO*)calloc(1, sizeof(NO));
p1 = px2;
px2->person->ID = 1; px2->person->age = 30;
px2->next = NULL;
px1 = px2;
px2 = (NO*)calloc(1, sizeof(NO));
px2->person->ID = 2; px2->person->age = 20;
px2->next = NULL;
px1->next = px2;
...
最佳答案
What's the difference in allocating memory with Malloc or Calloc in this example?
假设a
和b
都是正数且a * b
不溢出,则calloc(a, b)
和malloc(a * b)
只是calloc
将分配的内存初始化为全位零。没有别的了。
With Calloc the memory breaks, but with Malloc is fine!
无论您使用calloc()
还是malloc()
,无论它是否吵闹,您的程序都是错误的。您为 NO
分配内存,但随后取消引用它的 person
指针,而没有首先将其指定为指向有效对象。无论您使用哪种分配函数,结果都是未定义的。
关于c - 结构体动态链表中的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56348469/