...
Noncompliant Code Example
The standard {{ Wiki Markup strncpy()
}} function does not guarantee that the resulting string is null terminated \[ [ISO/IEC 9899:1999|AA. Bibliography#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.
Code Block | ||||
---|---|---|---|---|
| ||||
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { errno_t err = strncpy(a, source, 5); if (err != 0) { /* Handle error */ } } else { /* handle NULL string condition */ } |
Compliant Solution (strncpy_s()
)
The {{ Wiki Markup strncpy_s()
}} function copies up to {{n
}} characters from the source array to a destination array \ [[TR 24731|AA. Bibliography#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.
Code Block | ||||
---|---|---|---|---|
| ||||
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { errno_t err = strncpy_s(a, sizeof(a), source, 5); if (err != 0) { /* Handle error */ } } else { /* handle NULL string condition */ } |
...