Home > Software engineering >  How to safely deallocate pointer/reference to a heap allocated array
How to safely deallocate pointer/reference to a heap allocated array

Time:01-31

What the title says,

struct Foo
{
    int *arrayPointer;

    Foo (int * _arr) : arrayPointer(_arr) {}
};

int main()
{
    int *arr = new int[65536]; // edit to clarify, arr needs to be on heap, its massive
    
    Foo foo(arr);

    //do stuff

    delete [] arr; // is this correct, do i need a deconstructor?

    return 0;
}

My understanding is that arrayPointer is a normal pointer variable that gets destroyed when foo goes out of scope, but I want to be sure I am not risking some memory leak.

CodePudding user response:

delete [] arr; // is this correct

In a way, that is a correct way to deallocate a dynamic array owned by a bare pointer, but that isn't sufficient to cover all possible code paths, and using owning bare pointers should be avoided in the first place.

I want to be sure I am not risking some memory leak.

There is a risk of memory leak: If "do something" throws, then the delete expression won't be executed.

How to safely deallocate pointer/reference to a heap allocated array

By deallocating only within a destructor of a class that implements the RAII idiom. There is a container in the standard library that conveniently creates a dynamic array, and uses the RAII idiom: std::vector. I recommend using it.

CodePudding user response:

In a wider view, five decades of experience suggests that it is not, in fact, possible to use the new/delete approach to managing heap-allocated arrays (and other objects) safely.

You may, just, be able to write it correctly in a 20-line exercise, and the other answers and comments give suggestions for things to check. In any real-world program, there will be memory management errors; memory leaks, use-after-free, double free and so on. Some will be security issues, others "just" availability. At best, you can manage the risk, never eliminate it; using tools like valgrind to check the amount of memory leaked and make sure that it's acceptable, that sort of thing.

The alternative is to switch to another approach to managing heap-allocated space; however, that would mostly mean switching to another programming language, one which uses either garbage collection or borrow checking, so that's often not a workable solution.

  •  Tags:  
  • Related