3 ms·
You are confusing unsafe behavior with undefined behavior. He is not suggesting that a C compiler should prevent the above mistakes. He's suggesting that it sho
by sleepydog 11y ago
You are confusing unsafe behavior with undefined behavior. He is not suggesting that a C compiler should prevent the above mistakes. He's suggesting that it should document what code the compiler will emit in such cases. For example,
- reading past the end of an array will always segfault the program immediately. or reading past the end of an array will return (arrayType)0
- signed integer types must overflow according to two's complement. A compiler may not assume that, for instance, (int)x < (int)x + 1 is always true.
- uninitialized variables are zeroed out. That is, `int *x;` always produces a null pointer, `char y` always produces '0'
- A compiler may not remove any statements where it determines such an optimization would not change the behavior of the program. See http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buf...
Such a compiler would accept and compile any C program, and the programmer (and any static analysis tools) would have a better idea of the behavior of the output program.
- timmytokyo 11y ago> reading past the end of an array will always segfault the program immediately. or reading past the end of an array will return (arrayType)0 How would this work when you pass the array (i.e., the pointer) to a function? In order to do what you describe, every pointer would need to include bounds information. This would break the C ABI, so your code would no longer link with existing C libraries.
- raverbashing 11y agoExactly. It can't C makes you take the needed metadata to other parts of the program manually. It's not about being low-level, it's about having "pretend types" (like string or array) that are only actually a pointer with a tiny bit of syntactic sugar.
- sanxiyn 11y agoOP answered this on the thread. Pointer bounds are stored in a lookup table. Pointers are passed to functions according to C ABI, and bounds are retrieved by querying the lookup table by the pointer.