3 ms·
Can someone give a rationalization of why a "friendly" dialect of C should return unspecified values from reading uninitialized storage? Is the idea that all im
by twoodfin 12y ago
Can someone give a rationalization of why a "friendly" dialect of C should return unspecified values from reading uninitialized storage? Is the idea that all implementations will choose "0" for that unspecified value and allow programmers to be lazy?
I'd much rather my "friendly" implementation immediately trap. Code built in Visual C++'s debug mode is pretty reliable (and useful) in this regard.
EDIT: It occurs to me that this is probably a performance issue. Without pretty amazing (non-computable in the general case?) static analysis, it would be impossible to tell whether code initializes storage in all possible executions, and using VM tricks to detect all uninitialized access at runtime is likely prohibitively expensive for non-debug code.
- Scaevolus 12y agoThe change affects compiler optimization. The proposal changes many results from "undefined behavior" (compiler can do anything, including throwing away code before the statement executes) to "unspecified value", which means the statement might result in unknown values, but it can't remove the code. Read the linked articles in the post for a better treatment of what undefined behavior means and how compilers deal with it.
- zellyn 12y agoThe scope of an unspecified value's effect is limited to that particular value, whereas undefined behavior's effects are unlimited: http://en.wikipedia.org/wiki/Nasal_demons http://en.wikipedia.org/wiki/Nasal_demons
- kazinator 12y agoHowever, in practice, continuing with an unspecified value can have catastrophic consequences. And, also, undefined behavior can have nice consequences, like terminating with a diagnostic message, which is not a conforming way to implement unspecified behavior.
- PeterisP 12y agoBecause the current behavior of some compiler optimizations is that instead of returning unspecified values, it can assume that the code is unreachable (undefined behavior) and simply eliminate a bunch of normal, correct code that precedes reading unitialized storage. Guaranteed immediate trapping might be difficult on some platforms, but a specification that allows to return an unspecified value or trap immediately - that can be done anywhere.
- mark-r 12y agoHow do you propose to implement trapping on an uninitialized integer for example? You'd need significant hardware support, on the order of adding another bit to every memory location.