Reputation: 51
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
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