What's the better alternative to null-prefixed strings you are referring to, length prefixed?
What's the better alternative to null-prefixed strings you are referring to, length prefixed?
struct string_type {
char *ptr; // or char[]
size_t size;
}
because the whole idea of scrolling a whole string just to get its length it's an immense waste of CPU time. It has been optimized to death given that C does that for historical reasons¹, but still it's unwieldy and less safe.For instance, C strings make 0-cost string slicing impossibile: for instance, if you wanted to slice a string to get str[2;4] (i.e. a 2 char string from position 2), it would be simply
string slice { .data = str.data + 2, .size = 2 }
with the C++/Java/Rust/whatever approach. With C strings, given that you have to put a '\0' terminator at string end, you're forced to allocate memory and memcpy() the string, or to corrupt the original string.¹: size_t is much bigger than char (2x on 16 bit, 8x on 64 bit machines), so it made sense on a memory constrained machine like the PDP-11 to waste CPU time in order to save memory.
[0] And still are! For example, Python refers to them as such, see the "p" (lowercase p) character code here: https://docs.python.org/3/library/struct.html#format-strings
Some of them use a fat pointer instead, with a mix of counter, pointer to the end, and null terminator for C compatibility.