c - 结构体动态链表中的内存分配

标签 c list memory dynamic

本例中使用 Malloc 或 Calloc 分配内存有什么区别?
使用 Calloc 会导致内存损坏,但使用 Malloc 就可以了!
我的示例类似于(但具有许多值):

enter image description here

如果代码错误,该怎么办?

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?

假设ab都是正数且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/

相关文章:

c - 什么是不同的功能 : `malloc()` and `kmalloc()` ?

c - 1048576 以内的所有数字的位数都是错误的

c - 为什么下面的 C 代码输出 1?

c# - 当前上下文中不存在名称 '...'

python - 如何根据值与列表过滤字典

c - MAP_ANON 和 MAP_ANONYMOUS 都未在 C 中为 sys/mmap 声明

c - 平台设备驱动的Major编号是怎么分配的?

C素数分解(循环失败?)

C# LINQ 和涉及大型数据集的计算

python - Python 中 Bytearray 和 List 的区别