by unwind · 8y ago · 0 comments
if (w == 0 || h <= SIZE_MAX / w)
To me, that condition is just super-strange: if w is zero, the product w x h is zero too, so the entire allocation becomes pointless. Surely it should be: if (w != 0 && h <= SIZE_MAX / w)
or something? Having these kinds of discussions based on code that is confusing in itself just becomes too much, for me.One might, I suppose, decide that new_image will be exactly equivalent to the system malloc in this respect, in which case malloc(0) should be called when appropriate.
So you just want to make sure that w > 0 and w * h <= SIZE_MAX. But if w * h is large enough, it overflows, which would result in w * h <= SIZE_MAX being evaluated to true.
I agree that it is confusing though.
It might read a little funny, but it's actually quite correct with respects to what the code path should be expected to do. Valid dimensions should yield a valid pointer. Even if they're validly zero =)
Strictly wrong according to whom? At least not any C standard I know of.
Besides, even if the function did return a non-null pointer value (which it is allowed to do; the behaviour is implementation-defined) you aren't allowed to dereference it any more than a null pointer, making it hardly any more "valid", either.
It will probably break some assertions and assumptions though. Edit: I see that 8xde0wcNwpslOw (what a username) made the same point already.