grx00
grx00

Reputation: 51

There is a variable in scope. Is it undefined behavior to use this variable address outside of scope?

Here is a simple example.

void func()
{
    int* p = nullptr;
    if(p == nullptr)
    {
        int n;
        p = &n;
    }
    *p = 10; // undefined behavior??
}
int main()
{
    func();
}

There is no complie warning(visual studio 2019), is it "undefined behavior" to use "* p = 10" in this way?

Can it vary by compiler or by debug or release?

Upvotes: 2

Views: 105

Answers (1)

Bathsheba
Bathsheba

Reputation: 234845

Yes, the behaviour on dereferencing p is undefined.

Note also that the behaviour of even reading p once the object to which it points is out of scope is problematic: at this point it is an invalid pointer value, and formally the behaviour of reading p is implementation-defined, which can include a system generated runtime fault.

This latter point is often overlooked.

Upvotes: 5

Related Questions