strncpy(buf, str, buflen - 1);
if (buflen > 0)
buf[buflen - 1] = '\0'; strncpy(buf, str, buflen - 1);
if (buflen > 0)
buf[buflen - 1] = '\0'; strncpy(buf, str, n);
if (n > 0)
buf[n - 1]= '\0';
Which still checks `n` after calling `strncpy`, like you mentioned, but doesn't have the underflow problem.I was pretty proud of the "string for already allocated buffer" part of this lib tbh.
Anyway, i'll never take C for a four-hour coding challenge, but for bigger, non-web project, C is really awesome, thank to BLAS and to the fact that most languages implement mostly painless C ffi.
The only thing I wish the standard library would have is an `asprintf` which would return an allocated buffer. I've written my own, but the easy version utilizing regular `sprintf` requires calling `sprintf` twice (Once to get the length, and once to actually put the string in the allocated buffer). A regular supported version would be much more efficient.
https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/...
if (n > 0) {
strncpy(buf, str, n - 1);
buf[n - 1] = '\0';
}
Of course, the error isn't super huge considering if you're using a zero-length buffer as a null-terminated string you're going to have other problems. But they still do check for 0, so IMO it's worth correcting.