Home >Backend Development >C++ >What Happens When You Use `new[]` with a Size of Zero in C ?

What Happens When You Use `new[]` with a Size of Zero in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-16 16:26:10552browse

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:

  • You can allocate empty arrays using new[].
  • You should not dereference the returned pointer.
  • You should delete the allocated memory, even if it has zero size.

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!

Statement:
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