...
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 BUFSIZ
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."
Code Block | ||||
---|---|---|---|---|
| ||||
#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 | ||||
---|---|---|---|---|
| ||||
#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); } |
...