1572
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 simply 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 3:
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);
}
Example Language: Java (Bad)
FileInputStream fis;
byte[] byteArray = new byte[1024];
for (Iterator i=users.iterator(); i.hasNext();) {
String userName = (String) i.next();
String pFileName = PFILE_ROOT + "/" + userName;
FileInputStream fis = new FileInputStream(pFileName);
fis.read(byteArray); // the file is always 1k bytes
fis.close();
processPFile(userName, byteArray);
The code loops through a set of users, reading a private data file for each user. The programmer
assumes that the files are always 1 kilobyte in size and therefore ignores the return value from
Read(). If an attacker can create a smaller file, the program will recycle the remainder of the data
from the previous user and treat it as though it belongs to the attacker.
Example 4:
The following code does not check to see if the string returned by getParameter() is null before
calling the member function compareTo(), potentially causing a NULL dereference.
Example Language: Java (Bad)
String itemName = request.getParameter(ITEM_NAME);
if (itemName.compareTo(IMPORTANT_ITEM) == 0) {
...
}
CWE Version 4.14
CWE-754: Improper Check for Unusual or Exceptional Conditions
CWE-754: Improper Check for Unusual or Exceptional Conditions