0

Possible Duplicate:
Is delete[] equal to delete?

int main()
{
    char *ptr = new char[10];

    delete ptr;  // or delete [] ptr;
}

delete [] is for arrays, and delete is for a single object, right? So, it should be delete [] ptr; in the above code, but it seems delete ptr; is also ok. Weird?

Moreover,

int main()
{
    int x;
    cin >> x;
    char *ptr = new char[x];  //cannot make sure whether it is a char pointer or a pointer to an array, right?
    // delete ptr, or delete [] ptr;
}
Community
  • 1
  • 1
Alcott
  • 17,905
  • 32
  • 116
  • 173

1 Answers1

0

Right. Delete ptr by operator delete when you use operator new[] is undefined behaviour.

In the first alternative (delete object), the value of the operand of delete may be a null pointer value, a pointer to a non-array object created by a previous new-expression, or a pointer to a subobject (1.8) representing a base class of such an object (Clause 10). If not, the behavior is undefined.

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • And it is most likely a memory leak of n - 1. The second is an example of a complete memory leak, except when the main function returns, every modern OS will reclaim the application's memory and therefore make it moot, but that is a very bad practice. – pickypg Jul 27 '12 at 06:23