Its generally known that things on the stack are not initialized by default. I tried to prove that with a struct on the stack, but unexpectedly my pointer is initialized with null, but why? What is initializing this pointer?
#include <stdio.h>
#include <string.h>
struct strustri {
int var1;
char *var2;
};
int main()
{
struct strustri test1 = {
.var1 = 12,
.var2 = "Teststring",
};
struct strustri test2;
printf("test1.var1 is %d\n", test1.var1);
printf("test2.var1 is %d\n", test2.var1);
printf("test1.var2 points to %p\n", test1.var2);
printf("test2.var2 points to %p\n", test2.var2);
return 1;
}
And this is the output on my machine (Ubuntu 12.10):
test1.var1 is 12
test2.var1 is -1271814320
test1.var2 points to 0x400634
test2.var2 points to (nil)
I ran my example multiple times. I get another value for var1 everytime, but var2 is always points to zero (null pointer)…
Nothing is initializing it.
It’s just an artefact of whatever rubbish happens to be on your stack. Switch the order of the variable declarations, or add some more local variables, and you’ll get a different result.