Incorrect Calculation of Buffer Size (CWE-131) is another shameful member in the buffer overflow family. Buffer overflow is generally caused by copying or moving a piece of data to a smaller memory location hence overwriting some important data in the memory and corrupting the execution path of the computer. The most basic case of buffer overflow is not checking for buffer length before copying data. Even if the developer writes code to check length, there is still lots of room for error, this is exactly where incorrect calculation of buffer size fits in.
When the developer writes code or routine to check for the length of buffer to be moved or copied, sometimes the arithmetic is not exactly correct and this leads to incorrect calculation of size which in turn lead to buffer overflow. Most of the occurrences are due to human errors. A very common and well known flaw called the off by one is usually caused by developer forgetting about the NULL terminator at the end of the string or the fact that arithmetic starts at 0 rather than 1 within the programming language.
I will borrow an example from MITRE (example 4 on the page).
int *id_sequence; /* Allocate space for an array of three ids. */ id_sequence = (int*) malloc(3); if (id_sequence == NULL) exit(1); /* Populate the id array. */ id_sequence = 13579; id_sequence = 24680; id_sequence = 97531;
In this example, the intention of the developer is to create space for 3 integer (int), but coding mistake lead to only 3 bytes being reserved in memory. Each of the integer is 4 bytes in length, the three integers add up to 12 bytes. Now we have twelve bytes being put into 3 bytes which causes an overflow.
The solution to this problem is developer education and also review process. Peer review and also code scanner can help tremendously. Using more modern languages also tend to significantly reduce the possibility of these vulnerabilities.