by makecheck · 6y ago · 0 comments
Although C is usable on many types of hardware, interesting things could be done, e.g. on desktop OSes if certain hardware-specific extensions were made.
One of the things I wish we could do with our now-absurdly-large pointers (64-bit) is to reserve a handful of bits for other information such as the size. Sure it means we can’t store anything at location 2^64-1 but it wasn’t that long ago we only had 32-bit pointers and the 33rd bit is twice as many addresses all by itself so I think we can lose a few.
For example, if all allocations were rounded up to buckets of a certain size, the precise byte count would not need to be encoded in the pointer (just the number of buckets, requiring fewer bits). There could be a couple bits to give pointers a type for other interesting scenarios, e.g. perhaps a pointer identified as an “immediate value” that isn’t actually allocated at all, and it is “dereferenced” by treating its “address” as the “stored” value. There could even be a couple of bits to track use of common allocators (it would be so nice to simply know that a pointer was allocated by "malloc" vs. "new" for example).
In high-level languages, then, the syntax change would be not to identify arrays specifically but pointers with encodings that are “complete” (e.g. "char const complete*" or something), covering both stack arrays and dynamic buffers.
All that is needed is a mechanism for forming a fat pointer from a pointer and a length. In D this looks like:
int* p = cast(int*)malloc(length * sizeof(int));
if (!p) fatalError();
int[] a = p[0 .. length];
...
int x = a[length + 1]; // runtime error: buffer overflow
In C, this could be done via a macro with no additional core language changes. struct foo {
int a[10];
} f;
func(&f);