3 ms·
> I don’t think I could ever sleep the same at night after writing something like that In these situations, you likely know your hardware and know your compil
by OldHand2018 7y ago
> I don’t think I could ever sleep the same at night after writing something like that
In these situations, you likely know your hardware and know your compiler, so you can actually provide an answer for 4 of the questions. The last one is a situation where someone should tell you not to get cute in the code review.
I wrote C in telecom and finance and in both places we enforced a rule: when you define a structure, put a comment after each element that says what you think the structure offset should be, and at the end of the structure #define a constant that says what you think the size of the structure should be. In a code review, if anyone noticed something that didn't look right, you could talk about it. In testing, you could also check that sizeof(foo_s) == FOO_S_SIZE and fail if it wasn't.
In some of our code, we would test the size of various types and structures on startup and immediately exit if they weren't what we expected. We'd print type sizes to logs to help debugging if there was ever a problem. We were supporting a single code base that ran on big endian, little endian, X86, Itanium, SPARC, ARM. Compilers change, but automated tests of type and structure sizes catch things immediately.
It may sound like a lot of work, but it actually isn't at all. It also helps a lot with long-term maintainability.
- bzbarsky 7y ago> In some of our code, we would test the size of various types and structures on startup This is one of the things that C++ has actually improved a lot recently: doing this with static_assert is much nicer in terms of catching problems early... And yes, it's great for long-term maintainability.
- unwind 7y agoC has had standardized static assert since the C11 spec was released. See [1] for instance. [1]: https://stackoverflow.com/a/7287341 https://stackoverflow.com/a/7287341
- rramadass 7y agoNeat techniques. I had done similar stuff in some protocol code that i had a chance to write.