Home > Backend Development > C++ > Can C `new int[0]` Allocate Empty Memory, and If So, What Are the Implications?

Can C `new int[0]` Allocate Empty Memory, and If So, What Are the Implications?

Barbara Streisand
Release: 2024-12-26 13:07:10
Original
222 people have browsed it

Can C   `new int[0]` Allocate Empty Memory, and If So, What Are the Implications?

Curiosity Corner: Allocating Empty Memory in C

In the realm of C programming, an intriguing question arises: Can we allocate memory for an empty block, represented by new int[0].

Observations from a Test Application

A simple test application that prints the result of new int[0] reveals an output of 0x876c0b8, suggesting that memory is indeed being allocated.

Diving into the Standard

The C Standard provides guidance on this matter:

  • Zero-Sized Arrays: 5.3.4/7 states that a direct-new-declarator with an expression value of zero results in an allocation for an array with no elements.
  • Undefined Dereferencing: 3.7.3.1/2 warns that dereferencing a pointer returned for a zero-size request has undefined behavior.

Additional Considerations

  • Even with a zero-size request, the allocation may fail.
  • While allocation is permitted, dereferencing the returned memory is not legally well-defined across platforms.
  • You should delete the allocated memory, even if it has zero size.

Foot-Note Insights

An interesting foot-note from 3.7.3.1/2 reveals that the intention is to enable operator new() implementation using either malloc() or calloc(), which behave similarly with regards to zero-size requests. However, C differs from C by requiring a zero-size request to return a non-null pointer.

The above is the detailed content of Can C `new int[0]` Allocate Empty Memory, and If So, 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