0

I am still confused with the two functions malloc() and calloc()
As we know calloc() initialize the memory it allocates while malloc() doesn't.
But when I tried the following code, the result seemed unexpected.

typedef struct{
    int *val;
}Node;
int main()
{
    Node *q=(Node*)malloc(sizeof(Node));
    if(q->val==NULL) printf("malloc initialized memory\n");
    Node *p=(Node*)calloc(1,sizeof(Node));
    if(p->val==NULL) printf("calloc initialized memory\n");
}

The variables 'val' of val of p and q are both NULL. Isn't q->val uninitialized? Can anyone explain it to me? Thanks!

Liu
  • 413
  • 4
  • 11

3 Answers3

1

The malloc function does not initialize the memory it allocates. The contents will be indeterminate (and might seem "random" or "garbage").

If you want to zero-initialize the memory (which means that all pointers are NULL) then use calloc, or explicitly initialize the data.

Also note that in C you should not cast the return of malloc (and siblings).

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

When a variable is uninitialized, formally it means that its value is indeterminate. It could be any value, and 0 is just as random as any other value. Just because you read 0 doesn't necessarily mean the variable was initialized.

You're actually invoking undefined behavior by attempting to read q->val because 1) it was not initialized and 2) its address was never taken. Had its address been taken first you would not have undefined behavior unless the indeterminate value was a trap representation.

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Should I cast the return of calloc() or realloc() then?? If I should, why?? – Liu Feb 18 '19 at 15:52
  • @Liu [You should not cast the return value of `malloc` or `calloc`](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – dbush Feb 18 '19 at 15:53
0

The memory chunk returned via malloc(), contains indeterminate value. Attempt to use that value may incur unspecified result, as nothing about the value can be guranteed.

Quoting C11, chapter 7.22.3.4/P2

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    What Sourav is trying to say, I think, is that you can't trust your test to tell you definitively whether the memory was initialized or not. The bytes you're looking at might have been zero already. – Tim Randall Feb 18 '19 at 17:34