2 ms·
> You get this bug because the compiler doesn't know that the function will not return and therefor assumes that the de-reference will happen even if the value
by jancsika 7y ago
> You get this bug because the compiler doesn't know that the function will not return and therefor assumes that the de-reference will happen even if the value is NULL.
That would be even worse reasoning.
If the compiler doesn't know that the function will not return then how could it possibly implement optimizations that remove this code?
Not returning from a function is well-defined behavior in C.
Dereferencing a pointer after a NULL check condition which doesn't return is well-defined behavior.
I understand that changing an "implicit else" to an explicit else will clue modern compilers in to the fact that the code shouldn't be removed. Regardless, removing the code in the author's example is dead wrong (quite aside of what one makes of Linus' quite persuasive argument about not even touching NULL checks which follow undefined behavior).
Edit: clarification
Edit 2: Ok, I need a sanity check.
Let's forget about functions which never return. Instead, let us change "write_error_message_and_exit();" to "return 0;" which will signal an error message to the caller. Also, assume there is a "return 1;" somewhere below the author's example.
Is there any compiler at any optimization level which would optimize out my revised conditional?
- quelsolaar 7y agoif you replace write_error_message_and_exit with a return the problem should go away. If you think that is non-obvius, I agree, that's the problem. its very easy to do the wrong thing.