C++ valgrind 错误“大小 4 读取无效”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19785710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
valgrind error "Invalid read of size 4"
提问by Santosh Sahu
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".
程序的编译和运行不会出现任何问题,但使用 valgrind 时它会给出消息/警告“大小 4 读取无效”。
Any help to resolve the warning is most welcome
任何解决警告的帮助都是最受欢迎的
回答by Axel
n
is a local variable in fun1()
and is no more valid after exit of the function.
n
是局部变量,fun1()
退出函数后不再有效。
回答by Maroun
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.
局部变量仅在函数处于活动状态时存在。你返回的pf
是一个指向局部变量的指针。一旦退出函数,分配给变量的内存就会被释放,这会导致未定义的行为。
回答by SBI
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.
为了解决这个特殊情况:在 fun1 的堆上为 n 分配内存,并返回一个指向所述内存的指针,而不是你现在拥有的内存。
回答by Ivaylo Strandjev
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.
您正在返回一个局部变量的地址,而 valgrind 会警告您这一点。在 main 中访问此指针将调用未定义的行为。