The malloc
function is not supposed to initialize any value to any variable it is used on, like the malloc
does. Why then do I keep getting the initialized value of every other varibale to be 0, after using the malloc
function once in the program?
Here’s the code to reproduce the issue: –
#include <stdlib.h>
#include <stdio.h>
int main() {
int* ptr = malloc(sizeof(int));
int some_variable;
printf("%dn", some_variable); // prints 0
return 0;
}
Expected some garbage value to be printed but got 0. Even if malloc
does allocate 0 to every unintialized memory block, how are variables like some_variable
, completely out of the function’s scope getting affected?
Aditya Bhardwaj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.