Search code examples
c++memory-leaksdelete-operator

Memory Leak, source: float** binsRowPtrs = new float *[_nbins];


How do I delete this properly?

float** binsRowPtrs = new float *[_nbins];

The items are not dynamic created with new.

float** binsRowPtrs = new float *[_nbins];
for (int i = 0; i < _nbins ;i++)
{
    binsRowPtrs[i] = (float*) (bins[i].row(y).data);
}

Solution

  • The rule is:

    Call as many delete or delete[] respectively as new or new[] you used and on the exact same addresses.

    So if you just called new on binRowPtrs then you just need to call delete binRowPtrs.

    However, in the part of your code which you didn't show us, If you used dynamic allocation through new for each of the array elements then you need to loop through the array and call delete on each of the element as well.

    Note that ideally,
    In C++ You should use dynamic allocations only when you cannot avoid them &
    If et all you must, never use raw pointers, always use RAII through smart pointers to avoid the explicit memory management(you already noticed the perils of doing so in your case).