Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is freeing invalid pointers left undefined in C++?

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)?

like image 589
Destructor Avatar asked Nov 28 '22 04:11

Destructor


1 Answers

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
}
like image 147
imreal Avatar answered Dec 10 '22 12:12

imreal