3 ms·
> And I won't get started with C strings, which are just a historical BadIdea™. What's the better alternative to null-prefixed strings you are referring to, le
by MuffinFlavored 5y ago
> And I won't get started with C strings, which are just a historical BadIdea™.
What's the better alternative to null-prefixed strings you are referring to, length prefixed?
- dr_zoidberg 5y agoThose would be Pascal Strings (length at the start, then the bytes). Those make for very easy to write code, but they come with a few issues, but in general they are simpler and give better behavior than null-terminated strings. However, as for a bit of a historical bagagge, it seems we got used to null-terminated strings and just went on with them.
- pjmlp 5y agoOnly in C, even C++ has since the early days adopted proper strings on its standard library, initially the compiler specific ones from the early 90's, then the standard one.
- dr_zoidberg 5y agoSure, its just that these kind of strings were historically called Pascal-strings [0] because they were the way Pascal implemented strings. [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 https://docs.python.org/3/library/struct.html#format-strings
- pjmlp 5y agoNot all C++ string libraries use Pascal strings. Some of them use a fat pointer instead, with a mix of counter, pointer to the end, and null terminator for C compatibility.
- dr_zoidberg 5y agoThat's ingenious, but I don't think I've heard a name for those kind of strings.
- pjmlp 5y agoOne thing is certain, they aren't Pascal strings.
- qalmakka 5y agoNull terminated strings are the root cause of millions, if not billions of security vulnerabilities caused by buffer overflows. All modern languages have shunned null-terminated strings in favour of something in the likes of 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.