4 ms·
For strings, you need more than the allocated length: you need the current length too. Otherwise you end up with: - O(n) algorithms that are constantly scanni
by prirun 5y ago
For strings, you need more than the allocated length: you need the current length too. Otherwise you end up with:
- O(n) algorithms that are constantly scanning strings looking for a zero byte
- strings can't contain zero bytes
- strings have to contain one zero byte
- putting a zero byte in the middle of a string chops it off
- probably other nonsense I haven't thought of
Please don't adopt another half-assed solution just because it fits more easily into C's existing set of crap. That's how we got fake strings in the first place.
- WalterBright 5y agoThis solution has been in D for 20 years. It works very well. It is fully assed. It is very, very rare to see a buffer overflow in D because the use of these arrays is so easy, convenient, and robust. Not only does it virtually eliminate buffer overflows (when used), it is more efficient than 0 terminated strings. It does not need to scan the strings, nor does it need to load the string into memory to determine its length. I understand your concerns about mixing it up with 0 terminated strings. They are real, but have not been a particular problem in practice. What happens is one simply moves away from using 0 terminated strings. A zero terminated string can be converted to a length one with: a = s[0 .. strlen(s)]; Going the other way requires a memory allocation similar to what strdup() does.
- prirun 5y agoI read your article before posting, and it says: ----- void foo(char a[..]) meaning an array is passed as a so-called “fat pointer”, i.e. a pair consisting of a pointer to the start of the array, and a size_t of the array dimension. ----- I didn't see a "current length" mentioned. Is it there? Can I have a string with an allocated length of 20 bytes and a current length of 10 bytes, without using a looking for a zero byte?
- WalterBright 5y agoThe capacity value is not part of it. This proposal is not about memory management any more than 0 termination is about memory management. It is just about finding the end of the array.