An automatic object is an object whose lifetime is automatically managed. The storage for an automatic object, e.g. a local variable, is allocated
at the beginning of the enclosing code block and is deallocated at the end. This is commonly referred to as "allocated on the stack".
If the address of an automatic object is assigned to another automatic object of larger scope, a static or extern object, or if it is returned from
a function (using return
or an output parameter), then there will be a point where the address will point to an object that ceased to
exist. In that case, the address becomes invalid, and attempts to dereference the invalid address — trying to access the object that ceased to
exist — result in undefined behavior.
int *global = nullptr;
int* bar(int **out) {
int local = 42;
int *ptr;
global = &local; // Noncompliant: assigning the address of an object allocated on the stack to a global variable
{
int i = 9001;
ptr = &i; // Noncompliant: assigning the address of a stack-allocated object to an object that outlives it
}
*out = &local; // Noncompliant: returning the address of an object allocated on the stack (via output parameter)
return &local; // Noncompliant: returning the address of an object allocated on the stack
}