3 ms·
For that to happen the programmer had to be overly clever in the first place, in which case it is his own fault. If you stick to what is taught in any good tut
by aciuix 11y ago
For that to happen the programmer had to be overly clever in the first place, in which case it is his own fault.
If you stick to what is taught in any good tutorial/book, you don't even have to think about problems like this.
But if you decide to play with fire, then you should read the Standard and understand it.
- rcfox 11y agoIt's not hard to get into undefined behaviour territory with seemingly correct code. For example: signed integer overflow is undefined in C.
- aciuix 11y agoChecking future result of arithmetic where a wraparound is undesired or undefined, is a basic skill every C programmer should know. C is not a scripting language. If you use the tools available to you, and don't abuse the language, then it is fairly hard to cause undefined behavior.
- rcfox 11y agoIt's not always cut-and-dried: http://blog.regehr.org/archives/1139 http://blog.regehr.org/archives/1139
- aciuix 11y agoYou really shouldn't trust every article about C on the internet. Most of them make mistakes. If you are using gcc, you can start with the flag: -ftrapv. It does everything for you.
- rcfox 11y agoAh, but then you're not writing C anymore, you're writing GCC-flavoured C. If it helps: The author of that article, John Regehr, is a professor of computer science who spends a great deal of time studying undefined behaviour.
- deleted 11y ago[deleted]
- aciuix 11y agoYou are really something else: -Strawman argument. -Appeal to authority. Next time stick to the issue, you will find the debate will be much more rewarding for both parties.
- pgeorgi 11y agoAnd with every discussion of undefined behavior in C on this site, there's bound to be some user who's telling the world how they're "holding it wrong". I guess the best solution is to move to other languages (IIRC Ada and rust are relatively free from surprises in their UB) and let language lawyers optimize C to death (by attrition).
- pif 11y agoI don't get your point. Integer numbers have a finite valid range, and if you don't ensure that your program works only in this range, you are wrong. Whatever the compiler may do, it can't correct your error.
- wolf550e 11y agoMany programmers assume 2s complement and would like C to rely on this.
- rcfox 11y agoI guess it helps to give some context: unsigned integer overflow is defined. Some algorithms even exploit this behaviour to allow for simpler code. But even making sure that you stay within the valid range of your integer isn't necessarily enough; you need to check that you're still within the range without going outside of it.
- arielby 11y agoC's automatic conversions are more problematic than signed overflow itself.
- mikeash 11y agoWhat is seemingly correct about code that causes a signed integer overflow?