...
The standard functions strncpy()
and strncat()
copy a specified number of characters n
from a source string to a destination array. If there is no NULL null character in the first n
characters of the source array, the result will not be NULL terminated and any remaining characters are truncated.
...
Either the strcpy()
or strncpy()
function can be used to copy a string and a NULL null character to a destination buffer, provided there is enough space. Care must be taken to ensure that the destination buffer is large enough to hold the string to be copied and the NULL byte to prevent errors such as data truncation and buffer overflow.
Code Block | ||
---|---|---|
| ||
char *string_data; char a[16]; if (string_data == NULL) { /* Handle NULLnull pointer error */ } else if (strlen(string_data) >= sizeof(a)) { /* Handle overlong string error */ } else { strcpy(a, string_data); } |
...
Wiki Markup |
---|
The {{strcpy_s()}} function defined in \[[ISO/IEC TR 24731-1-:2007|AA. C References#ISO/IEC TR 24731-1-2007]\] provides additional safeguards, including accepting the size of the destination buffer as an additional argument (see [STR07-A. Use TR 24731 for remediation of existing string manipulation code]). Also, {{strnlen_s()}} accepts a maximum-length argument for strings that may not be NULL terminated. |
Code Block | ||
---|---|---|
| ||
char *string_data; char a[16]; if (string_data == NULL) { /* Handle NULLnull pointer error */ } else if (strnlen_s(string_data, sizeof(a)) >= sizeof(a)) { /* Handle overlong string error */ } else { strcpy_s(a, sizeof(a), string_data); } |
...
STR03-EX1: The intent of the programmer is to intentionally truncate the NULLnull-terminated byte string.
Risk Assessment
...
Wiki Markup |
---|
\[[ISO/IEC 9899-:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.21, "String handling <string.h>" \[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 2, "Strings" \[[ISO/IEC TR 24731-1-:2007|AA. C References#ISO/IEC TR 24731-1-2007]\] |
...