Versions Compared

Key

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

...

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

...

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 character in the first n characters of the source array, the result will not be NULL null-terminated and any remaining characters are truncated.

...

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 null-terminated.

Code Block
bgColor#ccccff
char *string_data;
char a[16];

if (string_data == NULL) {
  /* Handle null pointer error */
}
else if (strnlen_s(string_data, sizeof(a)) >= sizeof(a)) {
  /* Handle overlong string error */
}
else {
  strcpy_s(a, sizeof(a), string_data);
}

...