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;
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.
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.
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:
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With