why am I getting free(): invalid pointer error after program ends

Viewed 1478

Can somebody explain why I'm getting this error after program ends?

free(): invalid pointer

This is my code:

#include <iostream>
#include <memory>

int main()
{
    int a = 3;
    std::unique_ptr<int> up(&a);
    
    std::cout << a << std::endl;
    std::cout << *up << std::endl;
    
    std::cout << &a << std::endl;
    std::cout << up.get() << std::endl;
    
    return 0;
}
2 Answers
std::unique_ptr<int> up(&a);

The whole and entire purpose of std::unique_ptr, the only reason it exists, is so that when it goes out of scope and gets destroyed it automatically deletes whatever it's pointing to (assuming that it hasn't been moved from).

a was instantiated in function local scope, and not dynamic scope, hence attempting to delete, what was not newed, results in undefined behavior, and your crash.

This is a toy model of a unique pointer:

struct toy_ptr {
    int* p;
    ~toy_ptr() { delete p; }
};

("toy" because much more is needed, while this is only what is needed to reproduce your problem)

Now if you do this:

int main() {

    int a = 0;
    toy_ptr ptr{&a};
}

the toy_ptr takes ownership of a. Owning an object means: the toy_ptr is responsible for deleting it in its destructor. a was not allocated via new, hence attempting to delete it via delete &a invokes undefined behavior.

A unique_ptr is not a toy_ptr, but it also does take ownership of the pointer passed to the constructor and it does attempt to delete it in its destructor.

Related