Search code examples
c++memory-managementdelete-operator

Deallocator of arrays in c++ after modification of pointer


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?


Solution

  • 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.