valgrind error “Invalid read of size 4” [duplicate]

淺唱寂寞╮ 提交于 2019-12-10 21:30:05

问题


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:


nis 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!