Thursday, April 29, 2010

Diffrence between Strcpy(), Strncpy() and strcpy_s() Functions

Consider the code snippet:

char str[5];
strcpy (str, "Hello");

This will copy the word “Hello” to the character buffer ‘str’, but if i write ,

strcpy (str, "Hello world");

it will corrupt the memory in adjacent locations to str because the buffer str is only 5 bytes long and the source string is

11 bytes. The safe way is use the strncpy() function that takes the size of the destination buffer also as an argument.

strncpy (str, "Hello", 5);

or

strncpy (str, "Hello world",5);

Now, irrespective of the size of the source string, only 5 bytes will be copied to str.

Taking one step ahead, Microsoft released a set of more secure versions of these functions in Visual C++ 2005. This enhanced

set includes secure versions of functions like strcpy, ctime, fopen, scanf and many more.

The newer functions have the same function name appended by the “_s” suffix. e.g. the secure version for strcpy() is

strcpy_s(). Of course, there are differences in function prototypes. In the case of strcpy() and strcpy_s() they are:

char *strcpy( char *strDest, const char *strSrc );
errno_t strcpy_s( char *strDest, size_t nSize, const char *strSrc );

You will notice that strcpy_s() takes size of the destination buffer also, as an input parameter.

No comments:

Post a Comment