I'm starting to learn about dynamic memory allocation in C and so far everywhere I've read the malloc() function does NOT initialize the value of the newly allocated block.
Has this been changed in newer versions of C? C99 and C11?
I'm executing the following using Xcode and all values are being initialized with 0.
double *p = (double *) malloc(5 * sizeof(double));
printf("Address of p0 = %p | Valoe of p0 = %f\n", p, *p);
printf("Address of p1 = %p | Valoe of p1 = %f\n", p+1, *(p+1));
printf("Address of p2 = %p | Valoe of p2 = %f\n", p+2, *(p+2));
printf("Address of p3 = %p | Valoe of p3 = %f\n", p+3, *(p+3));
printf("Address of p4 = %p | Valoe of p4 = %f\n", p+4, *(p+4));
I thought this was true only for the function calloc().
Seems to be implementation defined behavior. On Visual Studio 2012, C compiler, I see no such initializations.
More importantly, read the "catch" of the selected answer in this question:
Why does malloc initialize the values to 0 in gcc?
Says, that the OS might "give" you zeroed values due to security reasons. As it seems, this is an implementation defined behavior.
Piece of advice: its not standard behavior and breaks portability of the code. Make sure you initialize the values and not depend on the data given by the OS .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With