Search code examples
c++referenceclangclionclang-tidy

clang not generating warning for "return a reference to a local object"


I have the following code:

int *&F(int *x) {
    int **p = &x;
    return *p;
}

int main() {
    int A[] = {0, 1, 2, 3, 4}, *y = A + 2, *&q = F(y);
    cout << *q << ' ' << *y << endl;
}

Now, i can see that we are returning the reference of x, but neither clang nor Clion (using clang-tidy) is generating warning for this code. Is this a problem for the static analysis that is too hard to follow a pointer and so to know that is pointing to or this is not returning a dangling reference?


Solution

  • You're not returning a reference to a local variable. You're returning a reference to whatever p points to (which, in this case, is a local variable but the static analysis doesn't see that).

    If you change the function to

    int *&F(int **x) {
        int **p = x;
        (*p) = (*p) - 1;
        return *p;
    }
    

    (changing the parameter to int ** instead of int *) then the problem (if any) isn't in this function at all but back with the caller.