Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

ISO/IEC 9899-1999 defines null pointers as "an integer constant expression with the value 0." Attempting to dereference a null an invalid pointer results in undefined program behavior, typically abnormal program termination. Given this, null invalid pointers should not be dereferenced.

Non-compliant Example

This example shows a function that negates an integer. If n is a null pointer, then when n is dereferenced the program may behave in an unexpected In this example, input_string is copied into dynamically allocated memory referenced by str. If malloc() }} fails, it returns an invalid (null) pointer that is assigned to {{str. When str is dereferenced in strcpy(), the program behave in an unpredictable manner.

Code Block
void negate(int *n) {
   *n = *n * -1;
}char *str = malloc(strlen(input_string)+1);
strcpy(str, input_string); /* What if malloc() fails? */

Compliant Solution

To correct this error, check the pointer returned by malloc() to ensure that n it is not a null pointer before attempting to dereference itnull. In addition to ths rule, this should be done in accordance with rule MEM32-C. Detect and handle critical memory allocation errors.

Code Block
void negate(int *n) {
  if(nchar *str = malloc(strlen(input_string)+1);
if (str == NULL) {
    /* Handle Allocation Error */
  }
  *n = *n * -1;
}strcpy(str, input_string);

Priority and Level

Dereferencing null pointers typically results in a denial of service condition.

Component

Value

Severity

 

Likelihood

 

Remediation cost

 

Priority

 

Level

 

References