PaeneInsula
PaeneInsula

Reputation: 2100

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.

Upvotes: 0

Views: 1412

Answers (2)

user97370
user97370

Reputation:

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.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272517

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.

Upvotes: 0

Related Questions