Difference in uses between malloc and calloc

前端 未结 7 463
花落未央
花落未央 2020-12-22 05:00
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions

7条回答
  •  旧巷少年郎
    2020-12-22 05:23

    All three loops in your program use only one struct Devices object at a time. The later ones allocate extra memory as though they are going to use multiple objects, but then keep overwriting the beginning of that memory. If you tried to use the object with ID 1 after setting up the object with ID 2, you would find there is no longer any object with ID 1.

    Instead, you could do something like this to treat the allocated memory as an array of structs:

    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for (i=0; i

提交回复
热议问题