Can Empty Arrays Be Allocated in C Using "new int[0]"?
In C , the usage of new operator to allocate memory is often employed. However, there arises a question regarding the allocation of empty arrays using new int[0]. Does this code allocate memory, and what does the standard specify about it?
Standard Perspective
According to 5.3.4/7 of the C standard, when the direct-new-declarator expression evaluates to zero, the allocation function assigns an array with no elements. Nonetheless, 3.7.3.1/2 emphasizes that dereferencing a pointer resulting from a zero-size request leads to an undefined behavior.
In Practice
Despite the standard's allowance for allocating empty arrays, it cautions that this operation may still fail. Consequently, one may only safely pass the allocated memory to array delete for deallocation, avoiding any direct memory access.
Special Note
A footnote in the standard suggests that the behavior mimics the approach of malloc() or calloc() in C, where a zero request returns a non-null pointer. This deviation from C ensures interoperability across platforms and allows for empty array allocation in C .
The above is the detailed content of Can `new int[0]` Allocate Memory in C , and What are the Implications?. For more information, please follow other related articles on the PHP Chinese website!