AutosarC++18_03-A18.5.10

Placement new shall be used only with properly aligned pointers to sufficient storage capacity

Required inputs: IR

Placement new constructs an object at a specific memory address. The memory must be properly aligned for the object type and have sufficient size. Misaligned storage or insufficient space causes undefined behavior, memory corruption, and crashes. Array new also requires space for array cookies that many implementations use to track array size.
Bad code (insufficient storage):
char buffer[2];  // ERROR: too small for int
int* ptr = new (buffer) int(42);  // Undefined behavior: buffer overflow
Bad code (misalignment):
char data[sizeof(double) + 1];
double* ptr = new (data + 1) double(3.14);  // ERROR: misaligned
Good code (sufficient aligned storage):
alignas(int) char buffer[sizeof(int)];      // OK: properly aligned
int* ptr = new (buffer) int(42);
Good code (using std::aligned_storage):
std::aligned_storage::type storage;
MyClass* ptr = new (&storage) MyClass();    // OK: correct alignment and size
Good code (array placement with cookies):
// Account for array cookie overhead (typically pointer-sized)
const size_t array_size = 10;
const size_t overhead = sizeof(size_t);     // Array cookie space
char buffer[array_size * sizeof(int) + overhead];
int* arr = new (buffer) int[array_size];    // OK: includes cookie space

Possible Messages

Key

Text

Severity

Disabled

array_new

Ensure to account for the overhead of array new expressions, i.e., storage required for array cookies

None

False

improper_alignment

Improper alignment {} when using placement new operator, intended storage has alignment {}

None

False

insufficient_storage

Insufficient space when using placement new operator: Object has {} bits, intended storage has {} bits

None

False

Options

check_array_cookies

check_array_cookies : bool = False

Check if storage space for array cookies is missing (needs StaticSemanticAnalysis).