Variable out of scope

Hi,

How do i see that a variable is out of scope in a checker? Like in the example below i'd like to see that p is dead when assigning 0 to it as x is out of scope.

void f() {
    int *p;
    {
        int x;
        p = &x;
    }
    *p = 0; // <-- error! p is dead.
}

//Anders

Hi Anders,

Hi,

How do i see that a variable is out of scope in a checker? Like in the example below i'd like to see that p is dead when assigning 0 to it as x is out of scope.

void f() {
    int *p;
    {
        int x;
        p = &x;
    }
    *p = 0; // <-- error! p is dead.
}

You are using the wrong words. "in scope" has a specific meaning in
C++ (a variable is in scope == the name can be referenced). The fact
that the compiler accepts " *p = 0 " means that p is in scope.

In the line indicated, p is not "dead". It is a perfectly fine pointer
with a non-null value. It does however point to a variable which *has*
gone out of scope (x). This looks like a use-after-free bug.

Csaba

Hi Anders,

Hi,

How do i see that a variable is out of scope in a checker? Like in the example below i'd like to see that p is dead when assigning 0 to it as x is out of scope.

void f() {
    int *p;
    {
        int x;
        p = &x;
    }
    *p = 0; // <-- error! p is dead.
}

You are using the wrong words. "in scope" has a specific meaning in
C++ (a variable is in scope == the name can be referenced). The fact
that the compiler accepts " *p = 0 " means that p is in scope.

In the line indicated, p is not "dead". It is a perfectly fine pointer
with a non-null value. It does however point to a variable which *has*
gone out of scope (x). This looks like a use-after-free bug.

Yes - and "x is out of scope" is the thing that Anders was trying to
ask/answer, so I don't think he was using the wrong words there.

But I don't know anything about the static analyzers to actually say
whether there's a good way to implement such a check.

There is not. We’ve wanted this “lifetime” or “scope” information for a while to find bugs like these. It’s an infrastructure issue. One thing that just occurred to me is that we could probably add this information as an enhancement to the CFG. We’re already inserting destructors for C++ objects; similarly lifetime “markers” could be added to the CFG for ordinary local variables. These markers would not be needed by all clients of the CFG (e.g., the frontend), but they would precisely model this problem very nicely for the static analyzer and similar clients. Adding this enhancement to the CFG probably wouldn’t be that hard at this point either, since the destructor support in the CFG has prepped much of the needed plumbing.