3 ms·
Well, yes: these are the original design constraints that led to null-terminated strings. The result is a data structure a bit like a linked list: finding the l
by pjc50 11y ago
Well, yes: these are the original design constraints that led to null-terminated strings. The result is a data structure a bit like a linked list: finding the length is an O(n) operation.
So long as all your operations on the string are char-at-a-time, and your first act is to check the char against zero, this works fine.
In fact, so long as you stay in the original UNIX batch processing model, where you're reading bytes from stdin and writing to stdout, the whole program works fine. Inconvenient buffer-size issues are avoided: don't keep intermediate buffers, just write to stdout a char at a time. (Have a look at lex/yacc generated code for this model, for example, with their not-easily-resettable parsers and trouble handling errors other than by calling `exit`).
The problem is not so much "string is not a type" as "buffers for composing strings are not a type".
- marvy 11y agoWhat do you mean by that last sentence?
- pjc50 11y agoRoughly the distinction Java makes between String and StringBuffer. I observed that buffer overflows require a buffer: if you do all your IO a character at a time, this is less risky. For security you need not "string first char + length of string" but "string first char + length of allocated region into which it is safe to write", which (unlike the length of the string) cannot be inferred from the string head pointer in any way.
- marvy 11y agothanks