26 ms·
Null terminated strings are the root cause of millions, if not billions of security vulnerabilities caused by buffer overflows. All modern languages have shunne
by qalmakka 5y ago
Null 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.