删除分配的指针(?)时“未分配释放的指针”

时间:2020-06-06 05:15:54

标签: c++ pointers c++14 clion

错误发生在“删除指针;”

代码:

#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 Catalina 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

2 个答案:

答案 0 :(得分:2)

您尚未分配任何指针。您也对术语感到困惑。这里的分配是指动态分配。在动态分配中,您分配内存,然后将该内存的地址分配给指针。内存分配有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释放它。否则,您会得到所谓的内存泄漏。未经检查的内存泄漏最终将意味着您的程序用完了要分配的内存。

答案 1 :(得分:0)

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