mikigal
mikigal

Reputation: 13

"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

Upvotes: 1

Views: 1915

Answers (2)

user10957435
user10957435

Reputation:

You should only delete pointers that have been allocated with new. Pointers to other objects will get invalidated (which is sort of like deleted, but not quite) automatically when the object goes out of scope so you don't have to worry about it.

Upvotes: 0

john
john

Reputation: 88007

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.

Upvotes: 3

Related Questions