News for hackers. Stuff that matters.
Re:What Every C Programmer Should Know About Undefined Behav... by Unklejoe on Thursday January 05, 2017 @08:33AM (#13326959)
Two things:

1. What's the proper way to do a NULL check? In the first example, they show how a NULL check could be optimized away, but I didn't see where they explained how to do it the right way. I might have just missed it though.

2. It would be nice if compilers offered a special optimization flag that performs most optimizations, but also “fills in the gaps” for non standard behavior by behaving how people expect. I realize that this would essentially be like each compiler implementing its own version of the standard in a way, but the reality is that if 99% of the people are making an assumption about how the compiler is going to do something, maybe that’s how the compiler should do it? Perhaps like a “speed+security” optimization flag. GCC already has some flags to handle certain questionable things such as strict aliasing, etc… Maybe something already exists, IDK. I guess the real solution would be to change the actual standard.

EDIT: A comment elsewhere provides a good response to my second point. It was along the lines of "which optimizations are okay then? Most optimizations broke code at some point".

I guess my response would be to only disable the ones that are the most common trouble makers. Another factor could be the performance gain vs amount of bugs it causes. I am reconsidering my second point though...

Re:What Every C Programmer Should Know About Undefined Behav... by lmm on Thursday January 05, 2017 @09:52AM (#13327490)
> 1. What's the proper way to do a NULL check? In the first example, they show how a NULL check could be optimized away, but I didn't see where they explained how to do it the right way. I might have just missed it though.

You need to not do * p at all if p is NULL (i.e. move the "int dead = * p" after the early return).

Re:What Every C Programmer Should Know About Undefined Behav... by hardlianotion on Thursday January 05, 2017 @08:36AM (#13326976)
To 1. I think if you were to do the null check and then dereference, the problem would go away. Oh - and use the variable holding the dereferenced data.
Re:What Every C Programmer Should Know About Undefined Behav... by EpicEng on Thursday January 05, 2017 @08:31PM (#13333194)
If the pointer is null and you go ahead and dereference it anyway then yes, that's dumb, and the compiler is free to remove the null check.