Alternative functions that limit the number of bytes copied are often recommended to mitigate buffer overflow vulnerabilities, for example:
strncpy()
instead ofstrcpy()
strncat()
instead ofstrcat()
fgets()
instead ofgets()
snprintf()
instead ofsprintf()
These function truncate strings that exceed the specified limits. Additionally, some functions such as strncpy() do not guarantee that the resulting string is null-terminated STR33-C.
Truncation results in a loss of data, and in some cases, leads to software vulnerabilities.
Non-Compliant Code Example
The standard function strncpy()
and strncat()
copy a specified number n
characters from a source string to a destination array. If there is no null character in the first n
characters of the source array the result is not be null-terminated and any remaining charactes are truncated
char *string_data; char a[16]; ... strncpy(a, string_data, sizeof(a));
Compliant Solution
Truncation resulting from a string copy operation should be treated as an error condition.
char *string_data; size_t string_len; char a[16]; ... if (!string_data) { if (strlen(a) < sizeof(a)) { strcpy(a, string_data); } else { /* handle error condition */ } } else { /* handle error condition */ }
Compliant Solution 2
Example using strcpy()
Compliant Solution 3
Example using strncpy_s()
Exception
An exception to this rule applies if the intent of the programmer was to convert a null-terminated byte string to a character array. To be compliant with this standard, this intent must be made clear statement in comments.
References
- ISO/IEC 9899-1999 7.21.2.4 The strncpy function
- ISO/IEC 9899-1999 7.21.3.2 The strncat function
- SAMATE Reference Dataset Test Case ID 000-000-004