Pointers to local var - unclear effect

Hi everyone I typed example to learn:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
...

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
Last edited on
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.
Thanks, I understand it now.

If compiler will be faster I have code like this:

- return localNumber
- compiler delete localNumber
- function get address from garbage
- print trash/rubbish

but is a bit slower
- return localNumber
- function get address from localNumber
- print localNumber
- compiler delete localNumber
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:
0
0
gcc/ibm:
512547305
0
xlc/ibm:
5
5
sun:
-71350040
-71350040

All these compilers are behaving correctly
Last edited on
Topic archived. No new replies allowed.