...
void replaceNumberAndPrint(int *x) {
printf("%d\n", *x);
}
int * getInt() {
int x = 5;
return &x;
}
int _tmain(int argc, _TCHAR* argv[])
{
replaceNumberAndPrint(getInt()); // -858993460 Ok, because point to local var (random piece of memory)
printf("%d\n",*getInt()); // 5 - is good because value have 5 but it pointed to local variable
return 0;
}
...
Why first replaceNumberAndPrint(getInt()); show some piece of memory,
and getInt() show local variable value? In my mind second must have value likewise first? Sorry for my English
The memory that was first used by x and that is set free when getInt() returns, still has the value of 5. Only if another program uses that memory, it will be overwritten. So sometimes *getInt() will give you the correct value (but never rely on it), and sometimes garbage.
The behavior of that program is undefined (because it attempts to dereference a pointer to a variable that no longer exists).
I'll run it through a few more compilers for fun (after replacing _tmain with main of course)
gcc/linux: