简体   繁体   中英

calloc, malloc and dynamic struct allocation

I am trying to dynamically allocate an array of structures in c so that I can refer to them the same as if I had done a static declaration. I understand that calloc() does the additional step of initializing all the allocated memory to 0. But, other than that, are the 2 completely interchangeable for the following code? If I am using fread() and fwrite() to get these data structures in and out of a file, does calloc() help or hinder this?

#define MAGIC   13
    struct s_myStruct {
int a[6000][400];
int b[6000][400];
int c[6000][400];
};

struct s_myStruct stuff[MAGIC];
vs
struct s_myStruct *stuff = calloc(MAGIC, sizeof(s_myStruct);

Thank you.

They're not the same. Declaring the data like this:

struct s_myStruct stuff[MAGIC];

will leave the memory uninitialized if you're declaring it in function scope (which you must be, given the second choice). Adding = {0} before the semicolon rectifies this.

The second choice, of using calloc, allocates the memory on the heap.

There's always a difference though: sizeof(stuff) will be 13 * sizeof(struct s_myStruct) in the first case, and the size of a pointer in the second case.

You really don't want to do the first one, as you'd be putting 13 * 3 * 6000 * 400 * 4 = 370MB on the stack.

But this has nothing to do with using fread and fwrite .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM