2

Possible Duplicate:
How does delete[] know it's an array? (C++)
How does delete[] “know” the size of the operand array?

suppose we have the following class

class Data
{
public:
    Data() : i(new int) { *i = 0; }
    ~Data() { delete i; }

private:
    int *i;
};

now we create array of 100 elements of type Data

Data* dataArray = new Data[100];

we know that operator new will call Data constructor for the 100 objects because it knows how many objects created, Now let's delete this array, if we say delete dataArray the destructor for first object only will be called even we know that the memory for the 100 objects we be released - will cause memory leak - and that because they allocated as one block, but if we say delete[] dataArray the destructor for the 100 objects will be called, but this is a dynmaic memory and i didn't specify how many object in there and as i know there is no overhead with the array to know how many objects in it, so how the runtime environment knows the number of objects to destruct before it free that memory?

Community
  • 1
  • 1
Muhammad
  • 1,598
  • 3
  • 19
  • 31
  • the allocator adds some magic numbers on the allocated block that tells how many elements there are - actual implementation depends on compiler – stijn Jul 13 '11 at 18:31
  • Wow, the brackets in the question name mangled that pretty bad. – Matt K Jul 13 '11 at 18:32
  • http://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array <-- This is probably a better candidate for the duplicate notice – bdonlan Jul 13 '11 at 18:35

3 Answers3

6

First, delete dataArray is illegal. It might destroy the first object. It might do nothing. It might crash. It might summon demons through your nose. Don't do it.

As for how delete [] determines how many elements to store, it depends on the C++ library implementation. Typically there's an element count right before the first element (this may be part of the metadata that's always associated with dynamic allocations, or it might be extra data added for delete []); the delete [] implementation will look at this count to determine how many times to call the destructor; it will then adjust the pointer to point before the element count before actually freeing the memory (this is one reason why delete dataArray can break badly).

bdonlan
  • 224,562
  • 31
  • 268
  • 324
1

It depends on what the compiler does, but basically 2 options :

  • Store data just before the actual objects (array size, allocated size), a la malloc.
  • Keep a global map of pointers associated with an array size.
user703016
  • 37,307
  • 8
  • 87
  • 112
0

That's why you need to use either operator delete or the operator delete[] in each particular case. They are not interchangeable and they do different things. The implementation keeps some compiler/library-specific bookkeeping information about each memory block that these operators use.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171