News for hackers. Stuff that matters.
Re:Considering C99 for Curl by hyc_symas on Tuesday November 22, 2022 @08:06PM (#33713760)
strlcpy() doesn't fix the problem of getting the length parameter wrong. The right solution is this:

    char *stecpy(char *d, const char *s, const char *e)
    {
      if (e) e--;
      while (d < e && *s)
        *d++ = *s++;
      if (d)
        *d = '\0';
      return d;
    }

    main() {
      char buf[64];
      char *ptr, *end = buf+sizeof(buf) ;
    
      ptr = stecpy(buf, "hello", end);
      ptr = stecpy(ptr, " world", end);
    }
As discussed here https://twitter.com/hyc_symas/status/1382298601641152513

The point is that the end of the buffer is invariant, there's no reason to screw around recalculating the length of remaining space after each copy into the buffer. This also fixes the nonsense of strcpy/strcat returning the same dst pointer that was passed in. By returning the pointer to where copying ended, you don't need a separate strcat function any more, nor do you have the Shlemiel The Painter problem with strcat.

There are no comments on this comment yet.