CWE-562

Return of Stack Variable Address. [Bad-Coding-Practices, Improper-Adherence-To-Coding-Standards]

Required inputs: IR

A function returns the address of a stack variable, which will cause unintended program behavior, typically in the form of a crash. Because local variables are allocated on the stack, when a program returns a pointer to a local variable, it is returning a stack address. A subsequent function call is likely to re-use this same stack address, thereby overwriting the value of the pointer, which no longer corresponds to the same variable since a function's stack frame is invalidated when it returns. At best this will cause the value of the pointer to change unexpectedly. In many cases it causes the program to crash the next time the pointer is dereferenced.
Demonstrative Examples
Example 1

The following function returns a stack address.

Example Language:C
    char* getName() {
        char name[STR_MAX];
        fillInName(name);
        return name;
    }
Excerpts from CWE [https://cwe.mitre.org], Copyright (C) 2006-2026, the MITRE Corporation. See section 9.4. "3rd-Party Licenses" in the documentation for full details.

Possible Messages

Key

Text

Severity

Disabled

possibly_leaking_reference_to_local_variable

Potentially leaking reference/pointer to local variable.

None

False

Options

additional_pointer_returns

additional_pointer_returns : set[str] = set()

Set of qualified names of member functions that are considered to return a reference or pointer to this or a subobject thereof. For this option to have effect, consider_pointer_returns has to be enabled, too.
 

allow_longer_living_local

allow_longer_living_local : bool = False

Whether assignment to a longer-living local variable should be accepted.
 

consider_constructors_as_capturing

consider_constructors_as_capturing : bool = False

Whether passing a reference or pointer to a local variable into a constructor should be considered as capturing. If the constructed object is assigned to some nonlocal object, a message is issued. If set to False, passing references or pointers into a constructor call has no effect on the analysis.
 

consider_pointer_returns

consider_pointer_returns : bool = False

Whether the return value of a function that returns a reference or pointer to its argument or to an object owned by its argument should be considered, when called on a local variable. E.g., std::string::data
 

consider_std_addressof

consider_std_addressof : bool = True

Consider a call to std::addressof as an address-taking operation.