Home >Backend Development >C++ >What Happens When You Allocate a Zero-Sized Array with `new int[0]` in C ?
C Memory Allocation with new int[0]
When allocating memory with the new operator, a common question arises: what happens when the requested array size is zero?
Surprisingly, the code snippet:
cout << new int[0] << endl;
outputs an address, indicating that memory was allocated. The C standard addresses this behavior:
Empty Array Allocation and Usage
As stated in 5.3.4/7 of the C standard, zero-sized arrays can be allocated but their usage is undefined, as per 3.7.3.1/2.
Handling Zero-Sized Arrays
Even if memory is successfully allocated, it is not guaranteed to be safe to dereference. There is no guarantee that it will point to valid memory.
Conclusion
While it is permitted to allocate empty arrays with new int[0], accessing or modifying the allocated memory has undefined behavior and should be avoided. Any such memory allocated must be deleted using delete, ensuring proper resource release.
It's important to note the standard requirement for operator new() to return a non-null pointer even for zero-sized requests, differing from the behavior of malloc(). However, the actual allocation may still fail.
The above is the detailed content of What Happens When You Allocate a Zero-Sized Array with `new int[0]` in C ?. For more information, please follow other related articles on the PHP Chinese website!