3

Possible Duplicate:
How does delete[] “know” the size of the operand array?

Assume i have an array of objects created dynamically

Car *newcars = new Car[10];
delete [] newcars;

How does the compiler know that there are 10 objects that need to be deleted.

Community
  • 1
  • 1
ckv
  • 10,539
  • 20
  • 100
  • 144

3 Answers3

3

Because new[] allocates more space than is needed for the objects. It also allocates space for the number of elements, and on debug systems maybe also the file and line number where the allocation took place, to help debug memory leaks.

Including extra space in every allocation for the memory manager's internal use is actually very common. When this happens and you have a buffer overflow, you may overwrite this extra space and whatever data the allocator kept there, resulting in "heap corruption".

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • How its implemented is up to the implementation - it could e.g. be using a map `(address -> infoStructure)` instead. – Georg Fritzsche Aug 02 '10 at 16:04
  • I didn't say that the extra space had to be adjacent to the array content... but it would be very unusual for it not to be. – Ben Voigt Aug 02 '10 at 16:05
0

Because the object has a destructor (even a default one) and it knows that there are 10 objects to destroy (they are deallocated as opposed to allocated with new). With the new keyword, it is typically allocated on the heap. The size is stored in the "head" segment.

0

The memory manager keeps records of what is allocated to each address. So in fact the compiler does not know at compile time (after all such array allocations can be dynamic) but the run time libraries know when the memory is allocated.

Elemental
  • 7,365
  • 2
  • 28
  • 33