AutosarC++18_03-A18.5.10¶
Placement new shall be used only with properly aligned pointers to sufficient storage capacity
Required inputs: IR
| Level | required |
|---|---|
| Target | implementation |
| Enforcement | automated |
Rationale
Placement new can be useful for cases in which allocation is required separately from type initialization, e.g. memory allocators, generic containers. Correct usage of placement new requires passing a pointer that:
- is suitably aligned
- provides sufficient storage memory
Violating above constrains will result in an object constructed at a misaligned location or memory initialization outside of the allocated bounds, which leads to undefined behaviour. An initial memory pointer used for placement new shall not be used after the call.
Example
//% $Id: A18-5-10.cpp 305629 2018-01-29 13:29:25Z piotr.serwa $
#include <cstdint>
#include <new>
void Foo() {
uint8_t c;
uint64_t *ptr = ::new (&c) uint64_t;
// non-compliant, insufficient storage
}
void Bar() {
uint8_t c; // Used elsewhere in the function
uint8_t buf[sizeof(uint64_t)];
uint64_t *ptr = ::new (buf) uint64_t;
// non-compliant, storage not properly aligned
}
See Also
- SEI CERT C++ Coding Standard [9]: MEM54-CPP: Provide placement new with properly aligned pointers to sufficient storage capacity
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¶
This rule shares the following common options: confidence, exclude_in_macros, exclude_messages_in_system_headers, excludes, extend_exclude_to_macro_invocations, includes, justification_checker, languages, post_processing, provider, report_at, severity
The following places define options that affect this rule: Stylechecks, Analysis-GlobalOptions