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?

7
  • 3
    Short answer: yes Commented Mar 5, 2020 at 17:32
  • 2
    "is undefined behavior?" Yes. Commented Mar 5, 2020 at 17:32
  • what the program will do can differ by compiler and by the phase of the moon, but it is always undefined Commented Mar 5, 2020 at 17:34
  • 1
    @NikosC.: Phew, I thought I had a huge refactoring job tomorrow. Commented Mar 5, 2020 at 17:37
  • 1
    fwiw, the edit didnt change anything on the question or on the answer. When your code has UB the compiler is not required to issue a warning or error Commented Mar 5, 2020 at 17:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 eel.is/c++draft/basic#stc-4 and DR 616
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.