Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is malloc( ) initializing the value of a newly allocated block of memory?

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().

like image 278
Italo Grossi Avatar asked Dec 01 '22 20:12

Italo Grossi


1 Answers

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 .

like image 183
Aniket Inge Avatar answered Dec 03 '22 09:12

Aniket Inge