Question

int* func()
{
   int* i=new int[3];
   return i; 
}

void funcc()
{
   int* tmp=func();
   //delete allocated memory after use
   delete[] tmp;
}

My opinion is that the compiler, when compiling funcc has no way to know that there is 3 int to be deleted, for example if func is in another file.

Was it helpful?

Solution

This is covered in the C++ FAQ lite:

[16.14] After p = new Fred[n], how does the compiler know there are n objects to be destructed during delete[] p?

Short answer: Magic.

Long answer: The run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the pointer, p. There are two popular techniques that do this. Both these techniques are in use by commercial-grade compilers, both have tradeoffs, and neither is perfect. These techniques are:

  • Over-allocate the array and put n just to the left of the first Fred object.
  • Use an associative array with p as the key and n as the value.

OTHER TIPS

That's the way delete is intended to be used, and it's fine. The array size is stored somewhere behind the scenes, so that delete[] will do the right thing wherever it happens.

However, juggling pointers like this is error prone: it's easy to lose the pointer before deleting the array, or for the logic to get so complicated that you end up deleting the same array twice. You'd be better off using a class to manage the array for you:

#include <vector>

std::vector<int> func() {
    return std::vector<int>(3);
}

void funcc() {
    auto tmp = func();
    // no need to do anything - the vector frees its memory automatically
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top