Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

The default global allocators will attempt to allocate sufficient storage for an object, and if successful, return a pointer with suitable alignment for that object. However, the default placement new operator simply returns the given pointer back to the caller without guaranteeing that there is sufficient space in which to construct the object , or ensuring that the pointer meets the proper alignment requirements. The C++ Standard, [expr.new], paragraph 16, nonnormatively states [ISO/IEC 14882-2014]:

...

(This note is a reminder of the general requirements specified by The the C++ Standard, [basic.stc.dynamic.allocation], paragraph 1, which apply to placement new operators by virtue of [basic.stc.dynamic], paragraph 3.)

...

In this noncompliant code example, a pointer to a short is passed to placement new, which is attempting to initialize a long. On architectures where sizeof(short) < sizeof(long), this it results in undefined behavior. This example, and subsequent ones, all assume the pointer created by placement new will not be used after the lifetime of its underlying storage has ended. For instance, the pointer will not be stored in a static global variable and dereferenced after the call to f() has ended. This assumption is in conformance with MEM50-CPP. Do not access freed memory.

...

This noncompliant code example ensures that the long is constructed into a buffer of sufficient size. However, it does not ensure that the alignment requirements are met for the pointer passed into placement new. To make this more obviousexample clearer, an additional local variable has been inserted.

...

This compliant solution ensures that the long is constructed into a buffer of sufficient size and with suitable alignment:

...

Risk Assessment

Providing improperly - aligned pointers to placement new can result in undefined behavior, including abnormal termination.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM54-CPP

Medium

Likely

Medium

P8

L2

...

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

...

[ISO/IEC 14882-2014]5.3.4, "New"
3.7.4, "Dynamic Storage Duration"  

 

...