logoalt Hacker News

arka2147483647last Tuesday at 5:42 PM2 repliesview on HN

Sadly, all the bug trackers are full of bugs relating to char*. So you very much do those by accident. And in C, fixed width strings are not in any way rare or unusual. Go to any c codebase you will find stuff like:

   char buf[12];
   sprintf(buf, "%s%s", this, that); // or
   strcat(buf, ...) // or
   strncpy(buf, ...) // and so on..

Replies

snickerbockerslast Tuesday at 7:47 PM

Thats only really a problem if this and that are coming from an external source and have not been truncated. I really don't see this as any more significant of a problem than all the many high level scripting languages where you can potentially inject code into a variable and interpret it.

There are certainly ways in which the c library could've been better (eg making strncpy handle the case where the source string is longer than n) but ultimately it will always need to operate under the assumption that the people using it are both competent and acting in good faith.

kccqzylast Tuesday at 9:02 PM

When you write such code your mental model is C strings, not fixed-width strings, the intended use case for strncpy.