我有一段非常简单的代码:
#include <iostream>
int main()
{
int *val = new int;
*val = 12;
std::cout << *val << std::endl;
delete &val;
return 0;
}
在此上运行Valgrind时,出现以下错误:
SUMMARY: 3 errors from 3 contexts (suppressed: 8 from 8)
1 errors in context 1 of 3:
Invalid free() / delete / delete[] / realloc()
at 0x1000ABB6D: free (vg_replace_malloc.c:533)
by 0x100000D1E: main (pointers.cpp:8)
Address 0x1048a09f0 is on thread 1's stack
in frame #1, created by main (pointers.cpp:4)
我如何删除val
有什么问题?
答案 0 :(得分:5)
如果尝试释放无效的内存,则会出现invalid free()
错误。
delete &val;
在这里,您尝试删除val
的地址,而不是val
指向的内存,这是错误的。
尝试如下操作。
delete val;