Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider v2.4 (sch jbop) (X_X)@==(Q_Q)@

...

Failure to properly terminate null-terminated byte strings can result in buffer overflows and other undefined behavior.

...

Noncompliant Code Example (strncpy())

Wiki Markup
The standard {{strncpy()}} function does not guarantee that the resulting string is null terminated \[[ISO/IEC 9899:1999|AA. C References#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.

In the first non-compliant noncompliant code example, ntbs is null terminated before the call to strncpy(). However, the subsequent execution of strncpy() may overwrite the null-termination character.

Code Block
bgColor#FFcccc
char ntbs[NTBS_SIZE];

ntbs[sizeof(ntbs)-1] = '\0';
strncpy(ntbs, source, sizeof(ntbs));

Wiki Markup
In the second non-compliantnoncompliant 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. C References#Schwarz 05]\].

...

Code Block
bgColor#ccccff
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 */
}

...

Noncompliant Code Example (realloc())

One method to decrease memory usage in critical situations when all available memory has been exhausted is to use the realloc() function to halve the size of message strings. The standard realloc() function has no concept of null-terminated byte strings. As a result, if realloc() is called to decrease the memory allocated for a null-terminated byte string, the null-termination character may be truncated.

The following non-compliant noncompliant code example fails to ensure that cur_msg is properly null terminated:

...