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

Confused about Valgrind errors after deleting off heap

我有一段很简单的代码:

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

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

delete &val;

此处您试图删除 val 的地址,而不是 val 指向的内存,这是错误的。 请改为尝试以下操作。

delete val;