valgrind error "Invalid read of size 4"
Solution 1
n
is a local variable in fun1()
and is no more valid after exit of the function.
Solution 2
Local variables exists only when the function is active. You're returning pf
which is a pointer to a local variable. As soon as you exit the function, the memory that was allocated to the variable is deallocated, this leads to undefined behavior.
Solution 3
Turning my comment into an answer: You are referencing a local variable from outside of a function after that function has returned. This means that even though, while running the program this seems to work because the stack stays untouched between the assignment. If you call other functions between the assignment and the print, it will most likely fail. I say "most likely" because what you're doing is undefined behavior, and can therefor not be predicted.
To fix this particular case: allocate memory for n on the heap inside fun1, and return a pointer to said memory instead of what you have now.
![Santosh Sahu](https://i.stack.imgur.com/JB0GQ.jpg?s=256&g=1)
Comments
-
Santosh Sahu almost 4 years
Here is my program
int* fun1(void) { int n=9; int *pf=&n; cout<<*pf<<endl; return pf; } int main(int argc, char *argv[]) { int *p=fun1(); cout<<*p; return 0; }
Compilation and running of program doesn't give any problems but with valgrind it gives message/warning "Invalid read of size 4".
Any help to resolve the warning is most welcome
-
gregn3 almost 8 yearsThis will make the variable accessible after exiting from the function:
static int n=9;