3 ms·
One of the surprisingly annoying minor things we implemented for some safe code were C routines for "safe arithmetic"--explicitly and carefully catching overflo
by angersock 12y ago
One of the surprisingly annoying minor things we implemented for some safe code were C routines for "safe arithmetic"--explicitly and carefully catching overflows due to multiplication and addition, for example.
This code proved invaluable when writing binary parsers designed to support "unsafe" mesh data coming off of the network--the file might be garbage, but we could at least safely parse it.
I'd go so far to say that if you are dealing with a binary format--especially a sane one which has length headers and chunks for rapid seeking--and you aren't using something similar, you are doing it wrong.
EDIT:
For the curious, you may find some of these bit-twiddling hacks to be of some use.
http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious http://graphics.stanford.edu/~seander/bithacks.html#IntegerL...
- TorKlingberg 12y agoRegehr, where this post is from, recently had an article about how to do safe arithmetic in C. http://blog.regehr.org/archives/1139 http://blog.regehr.org/archives/1139 As you say, it is surprisingly different to it get right, especially if you want good performance. A common mistake is checking for signed integer overflow after the fact. It is too late when undefined behavior has already happened.
- userbinator 12y ago> It is too late when undefined behavior has already happened. This seems more like a theoretical concern, as just about all the hardware out there is 2's complement and signed overflow wraps around in the usual way - because that's the simplest, most straightforward way to implement it. (This also means I think compilers that exploit this "loophole" in the language are seriously violating the principle of least surprise.) If you're working on the few exceptions to this, then integer overflow is probably going to be the least of your worries...
- zvrba 12y ago> One of the surprisingly annoying minor things we implemented for some safe code were C routines for "safe arithmetic" I'm surprised that something that necessary and tricky to implement still hasn't been considered for the C standard library.