删除堆后对Valgrind错误感到困惑

时间:2018-09-19 19:19:58

标签: c++ c++11 valgrind

我有一段非常简单的代码:

#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有什么问题?

1 个答案:

答案 0 :(得分:5)

如果尝试释放无效的内存,则会出现invalid free()错误。

delete &val;

在这里,您尝试删除val的地址,而不是val指向的内存,这是错误的。 尝试如下操作。

delete val;