Why freeing invalid left pointers undefined in C ++?

Consider the following program:

#include <iostream>
int main()
{
    int b=3;
    int* a=&b;
    std::cout<<*a<<'\n';
    delete a;  // oops disaster at runtime undefined behavior
}

Well, the behavior of the program is undefined according to the C ++ standard. But my question is, why is it left undefined? Why do C ++ implementations not give compiler errors or any warnings? Is it really difficult to determine the correctness of a pointer (does it mean to check if the pointer is returned new at compile time?) Is there any overhead to determine if the pointer is statically valid (i.e. compile time)?

+4
source share
4 answers

, , , :

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
}
+14

, , . , , , , , .

undefined, , , , .

+9

++ - ?

Clang .

:

$ scan-build clang++ main.cpp
scan-build: Using '/usr/bin/clang' for static analysis
main.cpp:7:5: warning: Argument to 'delete' is the address of the local variable 'b', which is not memory allocated by 'new'
    delete a;  // oops disaster at runtime undefined behavior
    ^~~~~~~~
1 warning generated.
scan-build: 1 bug found.

, , , Static Analyzer .

+7

:

new/delete , new, . . , delete , . , , delete , . , - undefined.

, , ?
new/delete , . - . , ; , .

, / , ++ .

+3

All Articles