Skip to content

Improper Memory Management

Rule ID

MI102

Definition

The software does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory.

Example

See one of the applicable code examples from CWE.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/* process message accepts a two-dimensional character array of the form [length][body] containing the message to be processed */
int processMessage(char **message)
{
  char *body;

  int length = getMessageLength(message[0]);

  if (length > 0) {
    body = &message[1][0];
    processMessageBody(body);
    return(SUCCESS);
}
else {
  printf("Unable to process message; invalid message length");
  return(FAIL);
}
}

The processMessage method receives a two dimensional character array containing the message to be processed. The two-dimensional character array contains the length of the message in the first character array and the message body in the second character array. The getMessageLength method retrieves the integer value of the length from the first character array. After validating that the message length is greater than zero, the body character array pointer points to the start of the second character array of the two-dimensional character array and memory is allocated for the new body character array. This example creates a situation where the length of the body character array can be very large and will consume excessive memory, exhausting system resources. This can be avoided by restricting the length of the second character array with a maximum length check

References

  • Common Weakness Enumeration: CWE-400
  • Common Weakness Enumeration: CWE-401