2

Here is the code

int *p = new int[10];
...
delete[] p;

How does the program know how many elements were there when delete[] was called?

Suppose we inserted the following code in between:

p++;

Will the program try to free one more element? Will it just stop at the 10th element?

Sergey
  • 1,168
  • 2
  • 13
  • 28
  • 8
    You would have Undefined Behavior, as `p` is no longer a pointer that was returned by `new[]`. It would be *bad*. – Drew Dormann Feb 24 '15 at 00:37
  • 5
    It's implementation defined, but usually a secret integer is stored just before the array in memory that contains its size. – Neil Kirk Feb 24 '15 at 00:38
  • and closely related to *both* questions, [How does `delete[]` know it's an array](http://stackoverflow.com/questions/703691/how-does-delete-know-its-an-array). – WhozCraig Feb 24 '15 at 00:46

1 Answers1

2

The allocator keeps one track of of how much memory you are allocating. This is usually stored in a "head" segment just before the memory that you are allocating. When you execute delete[], the de-allocator knows exactly how much memory to free.

If you modify the pointer, you would have a undefined behavior.

amchacon
  • 1,891
  • 1
  • 18
  • 29