I realise this code is faulty.
However, I came across some curious behaviour which I was wondering if somebody could explain.
Example 1 :
char *foo;
scanf("%s",foo);
printf("%s",foo);
Output is : (null).
Example 2 :
int i;
char *foo;
scanf("%s",foo);
printf("%s",foo);
Output is : val of foo !
Why would the presence of int i cause this to “work”?
foois a pointer, but you haven’t set it to point at any memory that you’ve allocated, so instead it just has a random value at startup, and hence is pointing at some random section of memory. Hence, anything could happen (i.e. undefined behaviour).The presence of
int ijust changes the position offooon the stack, and hence the particular random value that it has. You shouldn’t read anything meaningful into this differing behaviour, as it’s still undefined.