Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: NCCE wordsmithing

...

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), it this results in undefined behavior. This example, and subsequent ones, all assume the pointer created returned 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 example clearer, an additional local variable has c has also been inserteddeclared.

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

...