As a C programmer, you might to be required to copy string. There are standard libraries for this purpose. However, some are designed to avoid hacking, others are designed for performance. It is important to select a good API serving both purpose.
Buffer overflow attack is a popular approach where program overwrites the allocated memory buffer and it allows hackers to control the software. string copy is one of easiest way to create such loophole.
strcpy and strncpy both doesn't protect against buffer overflow. However, snprintf does. snprintf always appends null character to the end of string.
Example of zero terminated snprintf
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
int main()
{
char mystr[5];
snprintf(mystr, sizeof(mystr),"%s","apple");
printf("%s",mystr);
return 0;
}
===============================
[root@ubuntu /personal/testcode]# ./a.out
appl[root@ubuntu /personal/testcode]#
Note that in above output, snprintf ensured to zero terminate string and hence avoids buffer overflow.
this API is supported in Linux, Freebsd, MacOS and Windows . So, selecting this API over strlcpy will be better. Note that strlcpy avoids buffer overflow, but it is not supported in non-bsd platform
http://stackoverflow.com/questions/1775403/using-snprintf-to-avoid-buffer-overruns
http://stackoverflow.com/questions/4570147/safe-string-functions-in-mac-os-x-and-linux