Qt-Generic-NoReferenceToLocalVariableΒΆ

Do not return a reference or pointer to a local variable

Required inputs: IR

This rule detects when a function returns a reference or pointer to a local variable. Local variables have automatic storage duration and cease to exist when the function returns, making any reference or pointer to them dangling. This causes use-after-free errors and undefined behavior.
Bad code (returning reference to local):
int& GetValue() {
    int local_value = 42;
    return local_value;  // ERROR: reference to local variable
}

void ProcessValue() {
    int& ref = GetValue();  // ref now references destroyed object
    std::cout << ref;      // Undefined behavior!
}
Bad code (returning pointer to local):
int* AllocateNumber() {
    int number = 42;
    return &number;  // ERROR: pointer to local variable
}

void Use() {
    int* ptr = AllocateNumber();
    *ptr = 100;  // Undefined behavior!
}
Good code (return by value):
int GetValue() {
    int local_value = 42;
    return local_value;  // OK: returns value, not reference
}

void ProcessValue() {
    int value = GetValue();  // Safe: value is copied
    std::cout << value;
}
Good code (return dynamically allocated memory):
int* AllocateNumber() {
    int* number = new int(42);  // On heap, outlives function
    return number;
}

void Use() {
    int* ptr = AllocateNumber();
    *ptr = 100;  // OK: valid pointer
    delete ptr;
}

Possible Messages

Key

Text

Severity

Disabled

global_reference_to_local_var

Address of local variable escapes via global variable.

None

False

parameter_reference_to_local_var

Address of local variable escapes via parameter.

None

False

returning_reference_to_local_var

Return of reference/pointer to local variable.

None

False

Options