5 ms·
Can't remember where I read it because it was such a long time ago but one explicit benefit of null-terminated strings is that they take a single instruction to
by camperman 11y ago
Can't remember where I read it because it was such a long time ago but one explicit benefit of null-terminated strings is that they take a single instruction to check for the end on nearly all processors: jump if zero.
That allows for elegant constructions in C such as:
while (*p++ = *q++);
- justncase80 11y agoIt may be syntactically terse but I'm not sure it's elegant as you would need to do several checks before this line or else you could end up with some pretty major bugs. For example, you would need to ensure that sizeof p is >= sizeof q, or else you will end up with a buffer overflow. This then implies that q has a length and therefore a \0. So you will need to iterate through the string once to find the \0 (which may not be there). Failure to do this can lead to execution of arbitrary code, which is why null terminated strings are indefensible frankly.
- camperman 11y agoI read (and used) this during a more civilized age when everyone and his dog wasn't trying to get your program to execute arbitrary code, although I have still used the construct on a recent project on the Raspberry Pi and it worked just fine.
- justncase80 11y agoYou're very naughty ;)
- vardump 11y ago> That allows for elegant constructions in C such as: > while (*p++ = *q++); Elegant? It's short, if you don't include code for buffer management and validation. It maps very poorly to modern CPUs as-is, unless the compiler recognizes it as strcpy and replaces it with appropriate code. Luckily most compilers are capable of that. Otherwise loop termination condition causes (most?) compilers not to even try vectorization and an order of magnitude of performance is lost.
- camperman 11y ago"It maps very poorly to modern CPUs as-is" Indeed. When I said I read this a long time ago, I meant decades :)