3 ms·
""" Consider this code: if(p == NULL) write_error_message_and_exit(); *p = 0; If the compiler thinks that writing to NULL, is undefined, it can there
by jmillikin 4y ago
"""
Consider this code:
if(p == NULL)
write_error_message_and_exit();
*p = 0;
If the compiler thinks that writing to NULL, is undefined, it can therefore assume that since you are writing to p, p can’t be NULL. If p can’t be NULL, the entire if statement can be removed and after optimization the code looks like this:
*p = 0;
"""
The author has this backwards. The code in the first listing (test -> exit -> write) is correct, and will not be transformed in the way he claims.
The code which was wrong looked like this:
int pv = *p;
if (p == NULL)
write_error_message_and_exit();
GCC decided that since reading/writing NULL is undefined behavior, it should be allowed to treat `*p` as an assertion that `p` is non-null. Then it pruned any branches after the read that tested for `p == NULL`, including some that guarded more important parts of the logic.
Original coverage in LWN: https://lwn.net/Articles/342330/ https://lwn.net/Articles/342330/