488
showWidgets(WidgetList);
However, this code contains an off-by-one calculation error (CWE-193). It allocates exactly enough
space to contain the specified number of widgets, but it does not include the space for the NULL
pointer. As a result, the allocated buffer is smaller than it is supposed to be (CWE-131). So if
the user ever requests MAX_NUM_WIDGETS, there is an out-of-bounds write (CWE-787) when
the NULL is assigned. Depending on the environment and compilation settings, this could cause
memory corruption.
Example 2:
In this example, the code does not account for the terminating null character, and it writes one byte
beyond the end of the buffer.
The first call to strncat() appends up to 20 characters plus a terminating null character to fullname[].
There is plenty of allocated space for this, and there is no weakness associated with this first call.
However, the second call to strncat() potentially appends another 20 characters. The code does not
account for the terminating null character that is automatically added by strncat(). This terminating
null character would be written one byte beyond the end of the fullname[] buffer. Therefore an offby-
one error exists with the second strncat() call, as the third argument should be 19.
Example Language: C (Bad)
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
strncat(fullname, firstname, 20);
strncat(fullname, lastname, 20);
When using a function like strncat() one must leave a free byte at the end of the buffer for a
terminating null character, thus avoiding the off-by-one weakness. Additionally, the last argument
to strncat() is the number of characters to append, which must be less than the remaining space in
the buffer. Be careful not to just use the total size of the buffer.
Example Language: C (Good)
char firstname[20];
char lastname[20];
char fullname[40];
fullname[0] = '\0';
strncat(fullname, firstname, sizeof(fullname)-strlen(fullname)-1);
strncat(fullname, lastname, sizeof(fullname)-strlen(fullname)-1);
Example 3:
The Off-by-one error can also be manifested when reading characters from a character array within
a for loop that has an incorrect continuation condition.
Example Language: C (Bad)
#define PATH_SIZE 60
char filename[PATH_SIZE];
for(i=0; i<=PATH_SIZE; i++) {
char c = getc();
if (c == 'EOF') {
filename[i] = '\0';
}
filename[i] = getc();
}
In this case, the correct continuation condition is shown below.
CWE Version 4.14
CWE-193: Off-by-one Error
CWE-193: Off-by-one Error