Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: s/BUFSIZ/BUFFER_SIZE/g;

...

In this noncompliant code example, the function f() calls fread() to read nitems of type wchar_t, each size bytes in size, into an array of BUFSIZBUFFER_SIZE elements, wbuf. However, the expression used to compute the value of nitems fails to account for the fact that, unlike the size of char, the size of wchar_t may be greater than 1. Consequently, fread() could attempt to form pointers past the end of wbuf and use them to assign values to nonexistent elements of the array. Such an attempt results in undefined behavior 109.  . A likely consequence of this undefined behavior is a buffer overflow. For a discussion of this programming error in the Common Weakness Enumeration database, see CWE-121, "Access of memory location after end of buffer," and CWE-805, "Buffer access with incorrect length value."

Code Block
bgColor#ffcccc
langc
#include <stddef.h>
#include <stdio.h>
 #define BUFFER_SIZE 1024

void f(FILE *file) {
  wchar_t wbuf[BUFSIZBUFFER_SIZE];

  const size_t size = sizeof(*wbuf);
  const size_t nitems = sizeof(wbuf);

  size_t nread;

  nread = fread(wbuf, size, nitems, file);
}

...

Code Block
bgColor#ccccff
langc
#include <stddef.h>
#include <stdio.h>
#define BUFFER_SIZE 1024
 
void f(FILE *file) {
  wchar_t wbuf[BUFSIZBUFFER_SIZE];

  const size_t size = sizeof(*wbuf);
  const size_t nitems = sizeof(wbuf) / size;

  size_t nread;

  nread = fread(wbuf, size, nitems, file);
}

...