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)?
, , , :
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 }
, , . , , , , , .
undefined, , , , .
++ - ?
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 .
new/delete , new, . . , delete , . , , delete , . , - undefined.
new
delete
, , ?new/delete , . - . , ; , .
, / , ++ .