4 ms·
It certainly used to be in the old C89 days. I can't comment about C99 and above (because I don't know the spec well enough). I know there used to be a gcc patc
by david-given 10y ago
It certainly used to be in the old C89 days. I can't comment about C99 and above (because I don't know the spec well enough). I know there used to be a gcc patch which did exactly this.
The way it works is that the C89 spec defines memory in terms of objects, and it's illegal to even think about a pointer that doesn't point into an object (or to the byte after). That is, it's not just illegal to dereference it, you're not even allowed to create one.
So, because you know that every pointer must point at an object (or NULL), you encode the object and length of the object into the pointer. So pointers end up being a tuple of three words: object, object length, and offset. Now you have enough information to bounds check all accesses while still allowing pointer arithmetic within an object.
Of course, in real life, people do all kinds of wrong things which de-facto C allows but which de-jure C doesn't, such as pointer arithmetic between objects. But the spec does allow bounds checking.
(I abused this to implement a C to Perl compiler.)
Incidentally, fun fact: the 286 memory segmentation system supports mostly-bounds-checked pointer accesses in hardware.