2

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?

grx00
  • 41
  • 2

1 Answers1

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    It's easy to misread your answer. I first thought that "dereferencing and reading" were the same because I mixed up n and p. Maybe you could write: reading p is already undefined behavior, even without dereferencing it. This would mention the actions in their chronological order and this be simpler to understand. – Roland Illig Mar 05 '20 at 17:38
  • After the pointed-to object is destroyed the pointer does not behave as if it was uninitialized, i.e. as an *indeterminate value*. Rather it will become an *invalid pointer value*. Evaluating *indeterminate values* has undefined behavior, evaluating *invalid pointer values* has *implementation-defined behavior*, so in practice it would probably be fine on most platforms. (Ideally one should be able to find the behavior in the compiler documentation, but I am not sure that any compiler documents this properly.) See https://eel.is/c++draft/basic#stc-4 and [DR 616](https://wg21.link/cwg616) – walnut Mar 05 '20 at 18:10
  • @walnut Interesting difference: Likely because the value of a pointer to an object which has gone out of scope has at least a valid address format, in particular it is not a trap value. – Peter - Reinstate Monica Mar 05 '20 at 18:14