strcpy
Prototype
char * strcpy(char * dest, const char * src)This function copies the string pointed to by src (including the terminating null character) to the array pointed to by dest. The dest array must be large enough to hold the entire string, including the terminating null character.
Vulnerable example
#include <string.h>
int main(int argc, char* argv[])
{
char buffer[10];
strcpy(buffer, argv[1]);
return 0;
}Prevent
To prevent this vulnerability use the strlcpy function instead of strcpy. strlcpy is similar to strcpy, but it takes an additional argument that specifies the maximum number of characters to copy and ensure that the destination string is always null-terminated. This ensure that strlcpy does not write beyond the bounds of the destination buffer.
#include <string.h>
int main(int argc, char* argv[])
{
char buffer[10];
strlcpy(buffer, argv[1], sizeof(buffer));
return 0;
}It is also a good idea to check the length of argv[1] before calling strlcpy, to ensure that it is not longer than sizeof(buffer) - 1 characters. This can help to prevent a buffer overflow if the user passes a very long command-line argument to the program.
#include <string.h>
int main(int argc, char* argv[])
{
char buffer[10];
if (strlen(argv[1]) >= sizeof(buffer))
{
// Handle error - argv[1] is too long
}
else
{
strlcpy(buffer, argv[1], sizeof(buffer));
}
return 0;
}Last updated