Consider following program:
#include <iostream>
int main()
{
int b=3;
int* a=&b;
std::cout<<*a<<'\n';
delete a; // oops disaster at runtime undefined behavior
}
Ok, behavior of program is undefined according to C++ standard. But my question is why it is left undefined? Why implementations of C++ don't give any compiler errors or any warnings? Is it really hard to determine validity of pointer (means to check whether pointer is returned by new at compile time?) Is there any overhead involved to determine validity of pointer statically (i.e. compile time)?
It is impossible to determine what a pointer points to at compile time, here is an example to illustrate this:
volatile bool newAlloc;
int main()
{
int b=3;
int* a;
if(newAlloc)
{
a = new int;
} else {
a = &b;
}
std::cout<<*a<<'\n';
delete a; // impossible to know what a will be
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With