strcpy
Prototype
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
In this example, the buffer
array is defined with a size of 10 bytes, but the strcpy
function is used to copy the first command-line argument (which is passed to the program as argv[1]
) into the buffer without checking the length of the argument. If the first command-line argument is longer than 10 bytes, strcpy
will write beyond the bounds of the buffer
array, potentially causing a buffer overflow.
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.
In this example, the strlcpy
function copies at most sizeof(buffer) - 1
characters from argv[1]
to buffer.
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.
Last updated