Why is this an issue?
This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 3.8.1
Category: Required
Analysis Type: Undecidable,System
Amplification
Technically, a C++ object does not exist outside of its lifetime. However, for the purposes of this rule, a violation occurs whenever a memory
location that does not contain a live object of an appropriate type is accessed.
Rationale
It is undefined behaviour to access an object before it has been initialized or after its lifetime has ended (even if the memory occupied
by the object has not been released).
It is possible to refer to an object before its lifetime has begun, for example, by referring to a non-active member of a union.
Compliance with the rules cross-referenced by this rule helps to prevent lifetime violations.
Example
struct X
{
void doSomething() {}
};
void h( X * px )
{
px->~X(); // End the lifetime of *px
px->doSomething(); // Non-compliant
}
void g()
{
X a{};
auto & b = ( X{} = a ); // Immediate dangling of b
b.doSomething(); // Non-compliant
}
void f()
{
int32_t * pi = new int32_t { 42 };
delete pi;
std::cout << *pi; // Non-compliant
}
union u
{
int32_t a;
uint16_t b[ 2 ];
};
uint16_t u2()
{
u o;
o.a = 42;
return o.b[ 0 ]; // Non-compliant - b is not the active member
}
See the cross-referenced rules for further examples.
Copyright The MISRA Consortium Limited © 2023
Resources
Related rules
- S946, S3529, S5553, S6655 target the same defect as this rule but for a non-mission-critical
context.
- S6232 detects type-punning performed by accessing inactive member of the union.
- MISRA C++ 2023 Rule 3.8.2 - A function must not return a reference or a pointer to a local variable with automatic storage duration
- MISRA C++ 2023 Rule 3.8.3 - An assignment operator shall not assign the address of an object with automatic storage duration to an object
with a greater lifetime
- M23_158: MISRA C++ 2023 Rule 9.3.1 - The
union
keyword shall not be used
- M23_194: MISRA C++ 2023 Rule 15.3.3 - Handlers for a function-try-block of a constructor or destructor shall not refer
to non-static members from their class or its bases
- M23_388: MISRA C++ 2023 Rule 3.7.2 - Global variables shall not be used
- MISRA C++ 2023 Rule 3.8.4 - Member functions returning references to their object should be ref-qualified appropriately
- MISRA C++ 2023 Rule 6.5.2 - A for-range-initializer shall contain at most one function call
External coding guidelines