Why doesn't compile issue an error for code that results in undefined behavior
For example, articles usually say that if malloc and delete is paired up, or say that开发者_如何学Python it is wrong and don't do it.
But why doesn't compiler do some checking for us.
Will there be any cases that this kind of code is right and intended? Therefor compiler can't always say it's wrong to do it?
Or is there any technically difficulties for compiler to do that?
Many reasons. Off the top of my head.
Some undefined behaviour may have defined effects as an implementation specific extension.
Some undefined behaviour only occurs based on a program's environment or input, so the code might has the potential to cause undefined behaviour but won't necessarily do so.
Many instances of undefined behaviour are hard to diagnose. The may involve things that might potentially conflict in subsequent translation units. If they were easy to diagnose it is likely that the standard would require an implementation to issue a diagnostic as it does in many cases.
So, what would you say about this?
int* p = (int*)malloc(sizeof(p));
foobar(&p);
delete p;
foobar
is in a different compilation unit. You don't know what it does.
It is actually theoretically impossible to figure out if malloc is paired with delete in some cases. Just imagine the halting problem and a delete at the end of the program.
The compiler doesn't necessarily know whether the pointer was created using new
, malloc
, or if it's just a pointer to something on the stack. However, memory debuggers such as valgrind can find some of these errors.
精彩评论