In this section:

Overview

This error is generated whenever an attempt is made to dereference a NULL pointer.

CodeDescriptionEnabledReportedPlatform
READ_NULL

Reading NULL pointer

(tick)RuntimeWindows/Unix


Problem

The following code attempts to use a pointer that has not been explicitly initialized. Because the variable a is global, it is initialized to zero by default, which results in dereferencing a NULL pointer in line 10.

/*
 * File: readnull.c
 */
int *a;

main()
{
	int b, c;

	b = *a;
}

Diagnosis at Runtime

[readnull.c:10] **READ_NULL**
>>		 b = *a;
Reading null pointer: a

---- Associated Common Weakness Enumerations ----
CWE-476: Null pointer dereference

Stack trace where the error occurred:
		main() readnull.c, 10
**Memory corrupted. Program may crash!!**
  • Line 2: Source line at which the problem was detected.
  • Line 3: Description of the problem and the expression that is in error.
  • Line 5-6: CWE associated with this problem.
  • Line 8: Stack trace showing the function call sequence leading to the error.
  • Line 10: Informational message indicating that a serious error has occurred which may cause the program to crash.

Repair

A common cause of this problem is when a pointer that has not been assigned is used and initialized to zero. This is usually due to the omission of an assignment or allocation statement which would give the pointer a reasonable value.

The following code demonstrates one potential way to correct the example code:

/*
 * File: readnull.c (modified)
 */
int *a;

main()
{
	int b, c;

	a = &c;
	b = *a;
}

A second common source of this error is code that dynamically allocates memory, but then zeroes pointers as blocks are freed. In this case, the error would indicate reuse of a freed block.

A final common problem is caused when one of the dynamic memory allocation routines, malloc, calloc, or realloc, fails and returns a NULL pointer. This can happen either because your program passes bad arguments or simply because it asks for too much memory. A simple way of finding this problem with Insure++ is to enable the RETURN_FAILURE error code (see RETURN_FAILURE) and run the program again. It will then issue diagnostic messages every time a system call fails, including the memory allocation routines.

References

The table below shows Common Weakness Enumerations associated with this error.

CWEDescription
CWE-476Null pointer dereference
  • No labels