29 November 2012


If you aren’t a C programmer, bail now.

I’ve long wondered why strncpy and strncat were so brain-dead. Recently, I came across the answer. (Which made me go, “Oh...duh!”)

These functions look brain-dead when you try to use them to prevent buffer-overflows. But they weren’t designed to prevent buffer-overflows. They’re simply for copying a substring from the source. Their size parameters are simply meant to be the number of characters to copy from the source, not anything to do with the size of the destination buffer. The expectation, as with strcpy and strcat, is that you’ll figure out if the destination buffer is big enough beforehand.

Look into the strlcpy and strlcat functions from BSD if you haven’t already. They are designed for preventing buffer overflows. It also appears that the similar strcpy_s and strcat_s are on their way into the Standard.

(And now I’m wondering if there should be a strlncpy, that would take both the size of the destination buffer and a count of characters to copy from the source.)

You can also get by with snprintf as a safer replacement for strcpy if adding strlcpy or strcpy_s is not an option. Unfortunately, it can’t stand-in for strcat as easily since passing snprintf the same buffer as the destination and a source is a no-no.

No comments: