Steve Clamage said:
The net result of these rules is that you can always call free (once) with the
result you got from malloc.
So I take it MSVC 6's crash on:
char* x = new char[0];
delete [] x;
is most definitely non-compliant...?
Bear in mind the following differences:
A new-expression like
new T // T is some type
new T[size}
is a syntactical construct that causes memory to be allocated by the
memory allocation function associated with type T, followed by
contructor invocation(s) for the allocated object(s).
The C++ standard library contiains six different overloads of operator
new, a function that can be called explicitly to allocate raw memory.
You can also write your own overloads, and replace some of the default
versions. The rules are given in the C++ standard section 18.4.1 and
3.7.3. A new-expression invokes some version of operator new, as
explained in section 5.3.4.
C++ also inherits library functions malloc and free from C, which can
be called explicitly to manage raw storage. The C++ standard does not
require that malloc (or free) be used in the implementation of new (or
delete) expressions, or of operator new (or operator delete).
The code you show involves a new-expression and a delete-expression,
not direct calls to malloc or free.
I read section 5.3.4 to say that the expression
new T[0]
is ill-formed, for any type T. The standard requires a strictly
positive value for the constant-expression giving the array size. But
I tried a couple of compilers at full warning levels, and neither
complained about new char[0].
If the code is invalid, the standard imposes no requirements on the
behavior of the program. But it seems to me that an implemention
allowing the expression should also allow deleteing the pointer that
was returned.
Calling the operator new function explicitly is a different story,
however. The expression
operator new(0)
is valid. If the operation succeeds, it must return a unique address
for each call, which can be passed to the corresponding operator
delete().