1707
Example 2:
In the following example, it is possible to request that memcpy move a much larger segment of
memory than assumed:
Example Language: C (Bad)
int returnChunkSize(void *) {
/* if chunk info is valid, return the size of usable memory,
* else, return -1 to indicate an error
*/
...
}
int main() {
...
memcpy(destBuf, srcBuf, (returnChunkSize(destBuf)-1));
...
}
If returnChunkSize() happens to encounter an error it will return -1. Notice that the return value is
not checked before the memcpy operation (CWE-252), so -1 can be passed as the size argument
to memcpy() (CWE-805). Because memcpy() assumes that the value is unsigned, it will be
interpreted as MAXINT-1 (CWE-195), and therefore will copy far more memory than is likely
available to the destination buffer (CWE-787, CWE-788).
Example 3:
In the following example, the source character string is copied to the dest character string using the
method strncpy.
Example Language: C (Bad)
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(source)-1);
...
However, in the call to strncpy the source character string is used within the sizeof call to determine
the number of characters to copy. This will create a buffer overflow as the size of the source
character string is greater than the dest character string. The dest character string should be used
within the sizeof call to ensure that the correct number of characters are copied, as shown below.
Example Language: C (Good)
...
char source[21] = "the character string";
char dest[12];
strncpy(dest, source, sizeof(dest)-1);
...
Example 4:
In this example, the method outputFilenameToLog outputs a filename to a log file. The method
arguments include a pointer to a character string containing the file name and an integer for the
number of characters in the string. The filename is copied to a buffer where the buffer size is set
to a maximum size for inputs to the log file. The method then calls another method to save the
contents of the buffer to the log file.
Example Language: C (Bad)
#define LOG_INPUT_SIZE 40
// saves the file name to a log file
int outputFilenameToLog(char *filename, int length) {
CWE Version 4.14
CWE-805: Buffer Access with Incorrect Length Value
CWE-805: Buffer Access with Incorrect Length Value