Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the delete[] operator work with dynamically allocated memory returned through a pointer?

I'm wondering how the delete[] operators works with pointers returned by a function, rather then having the dynamic allocation in the same scope as the delete statement. Let's say I have a trivial function like this:

int *getArray()
{
    int *returnVal = new int[3];
    returnVal[0] = returnVal[1] = returnVal[2] = 0;
    return returnVal;
}

Now, when I need to use that array in my code, I would do the following:

int *vals = getArray();
// use values...
delete[] vals;

However, I'm wondering, how does the C++ compiler know how big the memory block that was allocated was (and thus how many memory elements to delete from vals)? Is this a valid technique, or would I have to delete each array value individually (like in the code below)?

int *vals = getArray();
// use values...
delete vals + 2;
delete vals + 1;
delete vals;
like image 252
Breakthrough Avatar asked Feb 22 '23 22:02

Breakthrough


2 Answers

You should only delete[] things obtained via new[]. In your code that's the value returned by getArray(). Deleting anything else is illegal.

However, I'm wondering, how does the C++ compiler know how big the memory block that was allocated was.

Each implementation stores the allocated size (and the type I think) in some way.

  • One common idea is to store the bookkeeping information (or an index of some sort) right before the actual allocated memory.
  • Another idea is to use the actual pointer as the key to a data structure that holds the required information

Of course this is overly simply explained (it's more like an explanation for C ). In C++ there is the added detail of destructors and whatnot.

like image 150
cnicutar Avatar answered May 09 '23 02:05

cnicutar


It's completely OK to delete memory out of the new[] scope. Read more here and here is the quote in case you are lazy to check the link.

[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:

  1. Over-allocate the array and put n just to the left of the first Fred object.
  2. Use an associative array with p as the key and n as the value.
like image 29
the.malkolm Avatar answered May 09 '23 04:05

the.malkolm