4

when we allocate memory dynamically using new operator for a int data type. it makes sense to use delete operator. For example if a code would like bellow : int *p=new int; delete p;

Here it makes sense to use delete . Here we can think like this that the block, p points ,delete/de-allocate that memory block . But for the bellow code :

int *p=new int[5]; delete[] p;

How does it make any sense to use delete[] here. I am asking this because p is not the name of the array. Here p is just a simple pointer which is pointing to the first element of the array memory block. Now how does delete[] works to delete the whole array.As here was not mentioned the size of the array. Then how does the statement delete[] p; delete the whole array.

  • 1
    Since `p` is just a pointer, the compiler and the standard library doesn't know that it points to the first element of an array, so you can't use the non-array `delete` operator. The compiler and standard library needs to know that you are freeing an array, which is why you need to use `delete[]`. – Some programmer dude Jul 22 '19 at 07:21
  • @Someprogrammerdude int reply to your: you can't use the non-array delete operator. But it works delete p; –  Jul 22 '19 at 07:59
  • 1
    Try creating an array of an object whose destructor needs to be called, and it will no longer work. `new` *must* be matched with `delete`, and `new[]` *must* be matched with `delete[]`. – Some programmer dude Jul 22 '19 at 08:26

1 Answers1

2

It's up to the compiler to figure out how to do that. One fairly standard way to do this is to store the size of the array in a technical header that precedes the allocated memory block.

NPE
  • 486,780
  • 108
  • 951
  • 1,012