Versions Compared

Key

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

Alternative functions that limit the number of bytes copied are often recommended to mitigate buffer overflow vulnerabilities, for example:

  • strncpy() instead of strcpy()
  • fgets() instead of gets()
  • snprintf() instead of sprintf()

These function truncate strings that exceed the specified limits. Additionally, some functions such as strncpy() do not guarantee that the resulting string is null-terminated .
Truncation results in a loss of data, and in some cases, leads to software vulnerabilities.

Non-Compliant Code Example

...

These two lines of code assume that gets() will not read more than BUFSIZ characters from stdin.  This is an invalid assumption and the resulting operation can result in a buffer overflow.

Code Block
char buf[BUFSIZ + 1];
gets(buf);

Non-Compliant Code Example

...

The standard function strncpy() and strncat() do not guarantee that the resulting string is null terminated.  If there is no null character in the first n characters of the source array pointed the result is not be null-terminated as in the following example:

...