Home > Backend Development > C++ > Can `new int[0]` Allocate Memory in C , and What are the Implications?

Can `new int[0]` Allocate Memory in C , and What are the Implications?

Patricia Arquette
Release: 2024-12-29 18:00:26
Original
863 people have browsed it

Can `new int[0]` Allocate Memory in C  , and What are the Implications?

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template