[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Having fun with the following C code (UB)



Shachar Shemesh <shachar@debian.org> writes:

> I will point out that it is not always is possible, and is quite often
> not easy. For example, the famous "undefined after NULL dereference"
> would probably cause a warning every time a function uses a pointer it
> was given without first validating its non-NULLness.

One can make a good argument that such checks are exactly what you should
be doing.

I used to be mildly opposed to this coding style since I felt like it led
to a lot of code clutter, but the more time I spend looking at security
vulnerabilities, the more I've come around to that approach.  I'm still
not sure that I want shared libraries calling assert(), but on the other
hand I can think of a lot of places where I'd rather have the shared
library call assert() than to go on and quietly do something bogus.
(Best, of course, is if you can return some sort of error in a reasonable
way, but that does force an often-awkward way of writing code.)

> My understanding of things is that undefined behaviors are fairly
> common, and almost always benign. Look at the following code:

> int add( int a, int b )
> {
>     return a+b;
> }

> Do you really want to get a "Warning: signed integer overflow yields
> undefined behavior" on this function?

I would certainly like to be able to enable such a thing.  I write a lot
of code where I'd love the compiler to double-check that I've established
bounds checks on a and b before doing the addition that guarantee that it
won't overflow.

Put a different way, the answer to your question is quite different if
that function were instead:

int compute_offset_into_network_packet( int a, int b )
{
    return a+b;
}

No?

-- 
Russ Allbery (rra@debian.org)               <http://www.eyrie.org/~eagle/>


Reply to: