Reputation: 5658
When I dynamically allocate memory in C with a function of the malloc
family is there some rule (coming from the C standard or the inner workings of an OS) as to what the initial value of that memory is?
int* ptr = malloc(sizeof (*ptr));
bool b = *ptr == 0; // always true?
Upvotes: 0
Views: 825
Reputation: 249404
The initial value of dynamically-allocated memory is indeterminate as far as the C standard is concerned. Some platforms may happen to give you zeros, others may happen to give you guard values like 0xEE everywhere, but none of this can be relied upon in a portable C program.
If you need zeros, the most conventional way is to use calloc()
, which has a chance of being optimized on some platforms.
Upvotes: 5