3 ms·
I'd have to think long and hard for the most beautiful code I've ever read, but I think the classic K&R "strcpy" comes pretty close: void strcpy(char *s, cha
by saagarjha 7y ago
I'd have to think long and hard for the most beautiful code I've ever read, but I think the classic K&R "strcpy" comes pretty close:
void strcpy(char *s, char *t) {
while (*s++ = *t++);
}
It's short, elegant, and quite readable to the trained eye–a bit sharp too, but if you use it right it's quite functional.
- jancsika 7y agoI've got a better code snippet: your exact same code snippet but for a language which will short circuit based on the lvalue of the assignment expression. Then t would never be able to overflow s (nor even eat its null terminator)
- jjnoakes 7y agoThe size of the buffer pointed to by s may be larger than the current string it holds. It may also be uninitialized.
- saagarjha 7y agoOr point to the wrong thing, or point to unmapped memory, or be const, or…there's a lot of things that can go wrong with this function.
- jjnoakes 7y agoThe things I listed are things the function does right as written but could not do if it worked the way suggested above. The things you listed are general concerns in C which are unrelated to both the correct implementation and the suggested changes.
- dhsysusbsjsi 7y agoThat’s what strncpy() is for
- WalterGR 7y agoI dunno. The security ramifications of those few lines of code make me squirm. It's like looking at a very beautifully constructed foot gun. I wonder how much damage that code has caused.
- goodcanadian 7y agoAt the time the code was written, the security ramifications were not quite the same as they are now. Even now, I would suggest that there are times where such a construction would be just fine.
- MaxBarraclough 7y ago> quite readable to the trained eye This kind of code is cute, but awful for readability. The author could easily (more easily!) have written the function to be very readable, but went for the cute ultra-compact style instead. The only reason it's at all readable is that it's solving such a simple problem. Write more complex functionality in that style, and you quickly get a nightmare. I believe MISRA C outright bans this kind of thing (three assignments with no sequence point), as it has no place in a codebase of real consequence. I understand that some C programmers pride themselves on being able to read this kind of code (far more impressive than being able to write it), but I see no reason for it in serious software work.