g()
and h()
assign the address of a local variable to the parameter and thereby expose the address to the caller. When these functions return, the local variable is freed, i.e., its place on the stack may be re-used.
Therefore, this is undefined behavior. In your example, it is a case of "use after free".
The calls to cout
and its operator<<
use some portion of the stack and overwrite the "former local variable".
There are several fixes for your sample code, depending on what you want to achieve:
If you want your function to modify the value of *p
of the main function, then do not introduce a new integer variable in g()
, but access the existing one:
void g(int *&x) {
*x=3;
}
Is basically the same as (1), but you without references instead of pointers.
void g(int &x) {
x=3; // x is no local variable but references the callers argument
}
- Allocate a new variable.
void g(int *&x) {
x = new int; // allocate int value on heap
*x = 3;
}
Because you pass a pointer as reference, the former pointer value will be overwritten, which may lead to a memory leak.
Same as (3) but using a return value and thereby reducing the risk of memory leaks:
int * g() {
int *x = new int; // allocate int value on heap
*x = 3;
return x;
}
To avoid memory leaks, you may use "automatic pointers", see http://www.cplusplus.com/reference/memory/unique_ptr/