0
#include <iostream>

using namespace std;

int main()
{
   int *p = new int[7];
   delete p;

   return 0;
}

Can i deallocate entire block of memory like this in C++? Thanks in advance.

  • `new` much be matched `delete`, and `new[]` must be matched by `delete[]`. – Some programmer dude Aug 29 '18 at 07:34
  • https://stackoverflow.com/questions/18046571/c-delete-array-memory-without-brackets-still-works ... in short: no, it does not work, it is undefined behaviour – Christian G Aug 29 '18 at 07:34
  • 2
    And if you're not required to, don't use `new[]` at all. Instead use either [`std::vector`](http://en.cppreference.com/w/cpp/container/vector) or possibly (depending on use-case and requirements etc.) [`std::array`](http://en.cppreference.com/w/cpp/container/array). – Some programmer dude Aug 29 '18 at 07:35
  • 1
    start using vectors and lists now. – Rizwan Aug 29 '18 at 07:36

1 Answers1

2

Deallocating array allocated with new[] without square brackets delete[] is undefined behavior by standard, that means it may seem to work sometimes or it may conjure demons out of your nose sometimes. There are no compiler extensions that make additional guarantees about it.

Use std::vector when you need dynamic arrays.

Öö Tiib
  • 10,809
  • 25
  • 44