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 vianew[]. In your code that’s the value returned bygetArray(). Deleting anything else is illegal.Each implementation stores the allocated size (and the type I think) in some way.
of some sort) right before the actual allocated memory.
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.