Wiki Markup |
---|
Null-terminated byte strings (NTBS) must contain a null-termination character at or before the address of the last element of the array before they can be safely passed as arguments to standard string-handling functions, such as {{strcpy()}} or {{strlen()}}. This is because these functions, as well as other string-handling functions defined by C99 \[[ISO/IEC 9899:1999|AA. References#ISOBibliography#ISO/IEC 9899-1999]\], depend on the existence of a null-termination character to determine the length of a string. Similarly, NTBS must be null terminated before iterating on a character array where the termination condition of the loop depends on the existence of a null-termination character within the memory allocated for the string, as in the following example: |
...
Wiki Markup |
---|
The standard {{strncpy()}} function does not guarantee that the resulting string is null terminated \[[ISO/IEC 9899:1999|AA. References#ISOBibliography#ISO/IEC 9899-1999]\]. If there is no null character in the first {{n}} characters of the {{source}} array, the result may not be null terminated. |
...
Wiki Markup |
---|
In the second noncompliant code example, {{memset()}} is used to clear the destination buffer; unfortunately, the third argument incorrectly specifies the size of the destination array \[[Schwarz 05|AA. References#SchwarzBibliography#Schwarz 05]\]. |
Code Block | ||
---|---|---|
| ||
char ntbs[NTBS_SIZE]; memset(ntbs, 0, sizeof(ntbs)-1); strncpy(ntbs, source, sizeof(ntbs)-1); |
...
Wiki Markup |
---|
The {{strncpy_s()}} function copies up to {{n}} characters from the source array to a destination array \[[TR 24731|AA. References#ISOBibliography#ISO/IEC TR 24731-1-2007]\]. If no null character was copied from the source array, then the {{n{}}}th position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated. |
...
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. References#ISOBibliography#ISO/IEC 9899-1999]\] Section 7.1.1, "Definitions of terms," Section 7.20.3.4 "The realloc function," and Section 7.21, "String handling <string.h>" \[[ISO/IEC PDTR 24772|AA. References#ISOBibliography#ISO/IEC PDTR 24772]\] "CJM String Termination" \[[ISO/IEC TR 24731-1:2007|AA. References#ISOBibliography#ISO/IEC TR 24731-1-2007]\] Section 6.7.1.4, "The strncpy_s function" \[[MITRE 07|AA. References#MITREBibliography#MITRE 07]\] [CWE ID 119|http://cwe.mitre.org/data/definitions/119.html], "Failure to Constrain Operations within the Bounds of an Allocated Memory Buffer," [CWE ID 170|http://cwe.mitre.org/data/definitions/170.html], "Improper Null Termination" \[[Schwarz 05|AA. References#SchwarzBibliography#Schwarz 05]\] \[[Seacord 05a|AA. References#SeacordBibliography#Seacord 05]\] Chapter 2, "Strings" \[[Viega 05|AA. References#ViegaBibliography#Viega 05]\] Section 5.2.14, "Miscalculated NULL termination" |
...