embedded software boot camp

C’s strcpy_s(): C11’s More Secure Version of strcpy()

Thursday, August 31st, 2017 by Michael Barr

Buffer overflows are a well-known port of entry for hackers and attackers of computerized systems. One of the easiest ways to create a buffer overflow weakness in a C program has long been to rely on the strcpy() function of the C standard library to overwrite data.

There’s a decent explanation of the problem at http://www.thegeekstuff.com/2013/06/buffer-overflow/. But the nutshell version is that you have a buffer of size X somewhere in memory that your code uses strcpy() to overwrite new nul-terminated strings. If an attacker can somehow feed a string longer than X bytes to your function then data beyond the bounds of the original array will be overwritten too: thereby rewriting code or data that serves some other purpose.

You should know that the new C11 update to the C programming language provides for a replacement “safe” version of this function, which is named strcpy_s(). The parameter lists and return types differ:

char *strcpy(char *strDestination, const char *strSource);

versus:

errno_t strcpy_s(char *strDestination, size_t numberOfElements, const char *strSource);

The new “numberOfElements” parameter is used by strcpy_s() to check that the strSource is not bigger than the buffer. And, when there is a problem, an error code is returned.

The Microsoft Developer Network website is one source of additional detail on this and other of C11’s “safe” functions.

Leave a Reply