3 ms·
It's not just their size, but wouldn't all arrays need know the address of their first element too? For example, consider a simple char buffer: char buf[51
by georgerobinson 11y ago
It's not just their size, but wouldn't all arrays need know the address of their first element too? For example, consider a simple char buffer:
char buf[512];
where we want to read x number of bytes from a file descriptor starting from a offset other than the first element:
read(fd, buf + 256, sizeof(buf)); // Whoops, incorrect sizeof, buffer overflow!
Could the compiler still detect this buffer overflow error without knowing the address of the first element in the array?
What about:
char *dst = buf + 256;
...
read(fd, dst, sizeof(buf));
perhaps the compiler could trace back all the calculations performed on the dst pointer to see whether this operation is valid?
- jerf 11y agoThe solution does involve storing a length, and this is called a Pascal string: https://en.wikipedia.org/wiki/String_%28computer_science%29#Length-prefixed https://en.wikipedia.org/wiki/String_%28computer_science%29#... Many, many, many moons ago, C strings won out over Pascal strings. If the competition was somehow re-run from scratch today, with modern machines, it would be no contest: Pascal strings would win. But there was a time when every byte was precious. And not just "a bit precious", but very precious.
- georgerobinson 11y agoWow, that's incredible, thanks for the link!
- TazeTSchnitzel 11y agoFor this case, you can use "fat pointers" that include the size of their destination.