Versions Compared

Key

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

...

This compliant solution uses the sizeof operator to correctly provide the object size and num_objs to provide the element count.:

Code Block
bgColor#ccccff
#include <stdint.h>
#include <stdio.h>
 
struct obj {
  char c;
  int i;
};
 
void func(FILE *f, struct obj *objs, size_t num_objs) {
  if (num_objs > (SIZE_MAX / sizeof(*objs)) ||
      num_objs != fwrite(objs, sizeof(*objs), num_objs, f)) {
    /* Handle error */
  }
}

...

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 BUFFER_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."

...