问题
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
回答1:
n
is a local variable in fun1()
and is no more valid after exit of the function.
回答2:
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.
回答3:
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.
回答4:
You are returning an address of a local variable and valgrind is warning you of that. Accessing this pointer in the main will invoke undefined behavior.
来源:https://stackoverflow.com/questions/19785710/valgrind-error-invalid-read-of-size-4