Home >Backend Development >C++ >What Happens When You Use `new[]` with a Size of Zero in C ?
Memory Allocation with C new[0]
In C , the new[] operator allows for the allocation of dynamic memory. However, what happens when the array size specified in the operator call is zero? A simple test program output suggests that memory appears to be allocated.
Standard Definition
According to the C standard, in 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."
Undefined Behavior
However, it is important to note that 3.7.3.1/2 states:
"The effect of dereferencing a pointer returned as a request for zero size is undefined."
This means that while it is technically possible to allocate an empty array with new[], accessing or modifying the memory it points to has undefined behavior.
Allocation Failures
Additionally, the standard mentions that even for zero size requests, the allocation can still fail.
Implications
In practice, this means that:
Foot-Note
The standard includes a foot-note indicating that the intent is to allow new[] to be implemented using functions like malloc() or calloc(), which also return non-null pointers for zero size requests.
The above is the detailed content of What Happens When You Use `new[]` with a Size of Zero in C ?. For more information, please follow other related articles on the PHP Chinese website!