0

This may sound a bit strange, but if I have the code uses delete [] as follows:

int main()
{
    int *test = new int(5);
    delete [] test //Does this work?
    // delete test (This is the standard syntax)
}

Of course, I tried to compile and run, and delete [] didn't return any errors. According to http://www.cplusplus.com/reference/new/operator%20delete[]/, delete[] operator first calls the appropriate destructors for each element in the array (if these are of a class type), and then calls an array deallocation function. I'm not 100% sure what array deallocation function is, but I presume this will not cause memory leak?

Ted
  • 469
  • 4
  • 16
  • It is undefined behavior. – R Sahu Mar 29 '18 at 15:28
  • A flaw in this specific test is that - on some compilers - `delete` and `delete[]` just happens to generate the same code for `int`s, but different code for class types with destructors. Makes it hard to test for UB. – Bo Persson Mar 29 '18 at 15:54

1 Answers1

4

Running delete [] for a pointer which was allocated with new is an undefined behavior. It may work, or may not, or may stop working at any moment, or may ruin your hardware. You have no guarantee.

alexeykuzmin0
  • 6,344
  • 2
  • 28
  • 51