CERT.MEM.PLACEMENTNEW.MISALIGNED

Provide placement new with properly aligned storage.

Vulnerability and risk

Passing improperly aligned pointers or pointers to insufficient storage to placement new expressions can result in undefined behavior, including buffer overflow and abnormal termination.

Mitigation and prevention

Do not pass a pointer that is not suitably aligned for the object being constructed to placement new. Doing so results in an object being constructed at a misaligned location, which results in undefined behavior. Do not pass a pointer that has insufficient storage capacity for the object being constructed, including the overhead required for arrays. Doing so may result in initialization of memory outside of the bounds of the object being constructed, which results in undefined behavior.

Finally, do not use placement new[] on any platform that does not specify a limit for the overhead it requires.

Noncompliant code example

Copy
#include <new>
  
void f() {
  char c; // Used elsewhere in the function
  unsigned char buffer[sizeof(long)];
  long *lp = ::new (buffer) long;
  
  // ...
}

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 example clearer, an additional local variable c has also been declared.

Compliant solution

Copy
#include <new>
  
void f() {
  char c; // Used elsewhere in the function
  std::aligned_storage<sizeof(long), alignof(long)>::type buffer;
  long *lp = ::new (&buffer) long;
  
  // ...
}

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