Comment by ryao

1 month ago

I would consider the use of signed integers for sizes to be wrong, but if you insist on using them in this example, just test for (n == INT_MAX). malloc itself uses size_t, which is unsigned.

I have been known to write patches converting signed integers to unsigned integers in places where signed arithmetic makes no sense.

The real problem is the fact compilers constantly screw up perfectly good code by optimizing it based on unreasonable "letter of the law" assumptions.

The issue of signed versus unsigned is tangential at best. There are good arguments in favor of the use of signed and unsigned integers. Neither type should cause compilers to screw code up beyond recognition.

The fact is signed integer overflow makes sense to programmers and works just fine on the machines people care to write code for. Nobody really cares that the C standard says signed integer overflow is undefined. That's just an excuse. If it's undefined, then simply define it.

Of course you can test for INT_MAX. The problem is you have to somehow know that you must do it that way instead of trying to observe the actual overflow. People tend to learn that sort of knowledge by being burned by optimizing compilers. I'd very much rather not have adversarial compilers instead.

  • I have been known to fix bugs involving signed integer overflow in C code others wrote.

    In any case, send your feedback to the C standard committee. They can change the standard. It would not be a bad change to make.