0

I come from a Java background and am still confused as to how pointers and stuff work. I have 2 examples.

int arr[10] = {};
delete[] arr;

Here, my compiler throws a warning about deleting arr.

int *arr = new int[4];
delete[] arr;

But it doesn't throw a warning here? Why is that?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Hat
  • 202
  • 1
  • 6
  • 1
    Each `new` has a corresponding `delete`. No `new` -> no `delete`. – KamilCuk Jun 13 '20 at 08:13
  • Because in the second case you are using `delete[]` correctly. Simply put, if you use `new[]` then at some point you need to use `delete[]`. BTW 'throw' has a specific meaning in C++ (to do with exceptions). Compilers don't throw warnings. – john Jun 13 '20 at 08:14

1 Answers1

3

In your first code, arr is statically allocated (on the stack), and will be automatically freed when going out of scope. Calling delete[] on statically allocated variables is pointless.

In your second code, arr is dynamically allocated on the heap, and will not automatically be freed when going out of scope, hence the need to call delete[] on it.

Get more information on the right usage of delete here: C++ and when to use delete

michaeldel
  • 2,204
  • 1
  • 13
  • 19