I was writing a program and facing this problem that the following function used to return garbage values:
int* foo(int temp){
int x = temp;
return &x;
}
When I modified it to this, it worked fine:
int* foo(int *temp){
int *x = temp;
return x
}
What was wrong with the first version?
The first version returns a reference to a local variable
xwhose storage is limited to the functionfoo. When the function exits,xcan no longer be used. Returning a reference to it is one instance of a dangling pointer.In the second version, you’re really only passing in and returning the same pointer value, which refers to memory which isn’t limited by the lifetime of the function. So even after the function exits, the returned address is still valid.
Another alternative: