Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Alternative functions that limit the number of bytes copied are often recommended to mitigate buffer overflow vulnerabilities. For exampleExamples include

  • strncpy() instead of strcpy()
  • strncat() instead of strcat()
  • fgets() instead of gets()
  • snprintf() instead of sprintf()

These functions truncate strings that exceed the specified limits. Additionally, some functions such as strncpy() do not guarantee that the resulting string is null-terminated. (See guideline rule STR32-C. Null-terminate byte strings as required.)

...

Code Block
bgColor#FFcccc
char *string_data;
char a[16];
/* ... */
strncpy(a, string_data, sizeof(a));

Compliant Solution (

...

Adequate Space)

Either the strcpy() or strncpy() function can be used to copy a string and a null character to a destination buffer, provided there is enough space. Care The programmer must be taken careful 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.

...

Wiki Markup
The {{strcpy_s()}} function defined in \[[ISO/IEC TR 24731-1:2007|AA. Bibliography#ISO/IEC TR 24731-1-2007]\] provides additional safeguards, including accepting the size of the destination buffer as an additional argument. (See guidelinerecommendation [STR07-C. 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.

...

If a runtime constraint error is detected by either the call to strnlen_s() or strcpy_s(), the currently registered runtime-constraint handler is invoked. See guideline recommendation ERR03-C. Use runtime-constraint handlers when calling functions defined by TR24731-1 for more information on using runtime-constraint handlers with TR 24731-1 functions.

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

CERT C++ Secure Coding Standard: STR03-CPP. Do not inadvertently truncate a null-terminated character array

Bibliography

unmigrated-wiki-markup

\[[ISO/IEC 9899:1999|AA. Bibliography#ISO/IEC 9899-1999]\] Section 7.21, "String handling <string.h>" \[[

ISO/IEC PDTR 24772|AA. Bibliography#ISO/IEC PDTR 24772]\] TR 24772 "CJM String Termination" \[[

ISO/IEC TR 24731-1:2007

MITRE CWE: CWE-170, "Improper Null Termination"

MITRE CWE: CWE-464, "Addition of Data Structure Sentinel"

Bibliography

Wiki Markup
|AA. Bibliography#ISO/IEC TR 24731-1-2007]\]
\[[MITRE 2007|AA. Bibliography#MITRE 07]\] [CWE ID 170|http://cwe.mitre.org/data/definitions/170.html], "Improper Null Termination," [CWE ID 464|http://cwe.mitre.org/data/definitions/464.html], "Addition of Data Structure Sentinel"
\[[Seacord 2005a|AA. Bibliography#Seacord 05a]\] Chapter 2, "Strings"

...