Search code examples
c++pointersc++14clion

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


The error occurs at the "delete pointer;"

Code:

#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;
}

Output:

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 (bundled with CLion)

Output from 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

Solution

  • You haven't allocated any pointer. You're also confused over terminology. Allocation here is refering to dynamic allocation. In dynamic allocation you allocate memory and you assign the address of that memory to a pointer. Memory is allocated with new

    So the correct version of your code is

    #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;
    }
    

    When you allocate memory with new you should free it with delete. Otherwise you get what is called a memory leak. Unchecked memory leaks would eventually mean your program runs out of memory to allocate.