This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 6.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