Versions Compared

Key

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

...

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 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 is in conformance with MEM30MEM50-CPP. Do not access freed memory.

Code Block
bgColor#FFcccc
langcpp
#include <new>
 
void f() {
  short s;
  long *lp = ::new (&s) long;
}

...

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

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MEM45-CPP

Medium

Likely

Medium

P8

L2

...

Related Guidelines

Bibliography

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

...