user2953119
user2953119

Reputation:

Allocation request of zero-size

I've been reading about allocation function (sec. 3.7.4.1 of N3797) and I came across with the following:

Even if the size of the space requested is zero, the request can fail.

It is unclear, because I requested zero size and It works fine. Could you explain the point of that rule?

Upvotes: 1

Views: 160

Answers (4)

alireza sadeghpour
alireza sadeghpour

Reputation: 689

it is one of c++ traits
when you do an wrong proccess it is Unpredictable

Upvotes: 0

Khouri Giordano
Khouri Giordano

Reputation: 1461

For historical reasons, malloc may return a non-null pointer when zero bytes are requested. MAY. A situation that ends up wanting a zero length array should just set the pointer to nullptr and use that as and indication to not free/delete it.

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172458

From the standard 5.3.4/7:

When the value of the expression in a direct-new-declarator is zero, the allocation function is called to allocate an array with no elements.

and from 3.7.3.1/2

[32. The intent is to have operator new() implementable by calling malloc() or calloc(), so the rules are substantially the same. C++ differs from C in requiring a zero request to return a non-null pointer.]

Also to add the operator new is not guaranteed to initialize memory to anything, and the new-expression that allocates an unsigned int without a new-initializer leaves the object with an indeterminate value.

Upvotes: 0

Dwayne Towell
Dwayne Towell

Reputation: 8583

The point is the implementation of an allocator is allowed to fail, even if the request size is zero. It doesn't say it has to fail, just that its allowed to fail if for some reason that would be convenient given the allocator's implementation. A typical reason would be that the overhead needed to manage the zero-length-allocation was too large for memory at the present time (say because other allocation had been performed).

Upvotes: 4

Related Questions