Another consequence derived from the dynamic memory
management in C is that memory initialization is only performed if requested
through the call to calloc
. In other words, when a new memory
portion is allocated with a call to malloc
, the portion made
visible to the program with its actual content. That is, no initial value is
assigned. Most likely, the memory contains the information that was stored
in its previous use.
This behavior is conceived to obtain the best performance in
a program. It is often the case that certain memory portions are requested,
but they are then initialized to some specific values from the program
itself. In this case, if malloc
returns the memory initialized,
the task is performed twice with a decrement in the performance. For this
reason, only the function calloc
performs this
initialization. As an example, the next code portion tries to print on the
screen as a string the garbage stored in the obtained memory
location.
char *string; string = (char *)malloc(100); printf("%s\n", string);