608
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:
The following code does not check to see if memory allocation succeeded before attempting to use
the pointer returned by malloc().
Example Language: C (Bad)
buf = (char*) malloc(req_size);
strncpy(buf, xfer, req_size);
The traditional defense of this coding error is: "If my program runs out of memory, it will fail. It
doesn't matter whether I handle the error or allow the program to die with a segmentation fault
when it tries to dereference the null pointer." This argument ignores three important considerations:
• Depending upon the type and size of the application, it may be possible to free memory that is
being used elsewhere so that execution can continue.
• It is impossible for the program to perform a graceful exit if required. If the program is
performing an atomic operation, it can leave the system in an inconsistent state.
• The programmer has lost the opportunity to record diagnostic information. Did the call to
malloc() fail because req_size was too large or because there were too many requests being
handled at the same time? Or was it caused by a memory leak that has built up over time?
Without handling the error, there is no way to know.
Example 4:
The following examples read a file into a byte array.
Example Language: C# (Bad)
char[] byteArray = new char[1024];
for (IEnumerator i=users.GetEnumerator(); i.MoveNext() ;i.Current()) {
String userName = (String) i.Current();
String pFileName = PFILE_ROOT + "/" + userName;
StreamReader sr = new StreamReader(pFileName);
sr.Read(byteArray,0,1024);//the file is always 1k bytes
sr.Close();
processPFile(userName, byteArray);
}
CWE Version 4.14
CWE-252: Unchecked Return Value
CWE-252: Unchecked Return Value