"Pointer being freed was not allocated" 同时删除分配的 (?) 指针

"Pointer being freed was not allocated" while deleting allocated (?) pointer

错误发生在"delete pointer;"

代码:

#include <iostream>

int main() {
    int i = 5;
    int* pointer = &i;
    *pointer = 0;
    std::cout << "Value: " << i << std::endl;
    delete pointer;
    std::cout << "This does not print" << std::endl;
    return 0;
}

输出:

Value: 0
untitled1(11320,0x106c20dc0) malloc: *** error for object 0x7ffeeeb00948: pointer being freed was not allocated
untitled1(11320,0x106c20dc0) malloc: *** set a breakpoint in malloc_error_break to debug

Process finished with exit code 6

OS: macOS 卡特琳娜 10.15.6 (19F101)

C++14

CMake:3.16.5(与 CLion 捆绑)

gcc -v 的输出:

❯ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.29)
Target: x86_64-apple-darwin19.5.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

您还没有分配任何指针。您还对术语感到困惑。这里的分配指的是动态分配。在动态分配中,您分配 memory 并将该内存的地址分配给指针。内存分配 new

所以您的代码的正确版本是

#include <iostream>

int main() {
    int* pointer = new int(5);
    *pointer = 0;
    std::cout << "Value: " << *pointer << std::endl;
    delete pointer;
    std::cout << "This does print" << std::endl;
    return 0;
}

当您使用 new 分配内存时,您应该使用 delete 释放它。否则你会得到所谓的内存泄漏。未经检查的内存泄漏最终将意味着您的程序用完内存来分配。

您应该只 delete 已分配 new 的指针。当对象超出范围时,指向其他对象的指针将自动失效(有点像删除,但不完全是),因此您不必担心。