Lurker News
Preferably an elegant snippet rather than an entire (well engineered) codebase.

Comments (380) 116 threads

Show all comments

Showing thread 9 of 116

saagarjha3 replies#
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.
jancsika1 reply#
I'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)

jjnoakes2 replies#
The size of the buffer pointed to by s may be larger than the current string it holds. It may also be uninitialized.
saagarjha1 reply#
Or 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.

Continue this thread — 1 reply

dhsysusbsjsi4 replies#
That’s what strncpy() is for

Continue this thread — 4 replies

WalterGR1 reply#
I 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.

goodcanadian2 replies#
At 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.
hestefisk#
I would say it’s clever but not beautiful code.
garmaine#
Nit, but an important one: the security ramifications were just as large than as now, they were just largely unknown at the time.
MaxBarraclough#
> 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.