Foo* set = new Foo[100];
// ...
delete [] set;
You don\'t pass the array\'s boundaries to delete[]
. But where is that information stor
ONE OF THE approaches for compilers is to allocate a little more memory and to store a count of elements in a head element.
Example how it could be done:
Here
int* i = new int[4];
compiler will allocate sizeof(int)*5
bytes.
int *temp = malloc(sizeof(int)*5)
Will store "4" in the first sizeof(int)
bytes
*temp = 4;
and set i
i = temp + 1;
So i
will points to an array of 4 elements, not 5.
And deletion
delete[] i;
will be processed in the following way:
int *temp = i - 1;
int numbers_of_element = *temp; // = 4
... call destructor for numbers_of_element elements
... that are stored in temp + 1, temp + 2, ... temp + 4 if needed
free (temp)