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

I'm wondering how delete [] operators work with pointers returned by a function, and not with dynamic allocation in the same scope as the delete operator. 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 that I need to use this array in my code, I would do the following:

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

However, I wonder how the C ++ compiler knows how big the allocated block of memory was (and therefore how many memory elements need to be removed from vals )? Is this a valid method or will I need to delete each array value separately (for example, in the code below)?

 int *vals = getArray(); // use values... delete vals + 2; delete vals + 1; delete vals; 
+4
source share
4 answers

You should only get delete[] things obtained with new[] . In your code, the value returned by getArray() . Removing anything else is illegal.

However, I wonder how the C ++ compiler knows how big the allocated memory block is.

Each implementation saves a certain size (and the type that I think) in some way.

  • One general idea is to store accounting information (or an index of some sort) until the actual allocated memory.
  • Another idea is to use the actual pointer as a key to the data structure that contains the required information.

Of course, this is too easy to explain (this is more like an explanation for C). In C ++, there is an added detail to destructors and much more.

+4
source

It is completely normal to remove memory from a new area []. Read more here and here is a quote in case you are lazy to check the link.

[16.14] After p = new Fred [n], how does the compiler know that during deletion there are n objects that will be destroyed [] p?

Short answer: Magic.

Long answer: the runtime system stores the number of objects, n, where it can be found if you only know the pointer, p. These are two popular methods. Both of these methods are used by commercial-class compilers, both have trade-offs and neither. These methods:

  • Override the array and place n only to the left of the first Fred object.
  • Use an associative array with p as the key and n as the value.
+2
source

Short answer: it works.

In fact, the only valid thing related to the pointer obtained from new[] is delete[] it.

The compiler will add additional information to the memory that it receives from the OS so that it can track how significant the allocated blocks are. This information allows data that can only be identified by a pointer to be properly destroyed and freed.

+2
source

You should not and should not delete each item in turn. You get undefined results. When allocating memory, the compiler includes overhead.

0
source

All Articles