Versions Compared

Key

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

...

Code Block
bgColor#ccccff
langc
char *source = "0123456789abcdef";
char ntbs[NTBS_SIZE];
/* ... */
if (source) {
  if (strlen(source) < sizeof(ntbs)) {
    strcpy(ntbs, source);
  }
  else {
    /* Handle string too large condition */
  }
}
else {
  /* Handle NULL string condition */
}

Compliant Solution (strncpy_s()C11 Annex K)

The C11 Annex K strncpy_s() function copies up to n characters from the source array to a destination array [ISO/IEC TR 24731-1:20079899:2011]. If no null character was copied from the source array, then the nth position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated.

...

CERT C++ Secure Coding StandardSTR32-CPP. Null-terminate character arrays as required
ISO/IEC TR 24731-1:20079899:2011KSection 6.7.1.4, "The strncpy_s Function"
ISO/IEC TR 24772:2013String Termination [CMJ]
ISO/IEC TS 17961 (Draft)Passing a non-null-terminated character sequence to a library function that expects a string [strmod]
MITRE CWECWE-119, Failure to constrain operations within the bounds of an allocated memory buffer
CWE-170, Improper null termination

...