Versions Compared

Key

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

Attempting to dereference an invalid pointer results in undefined behavior, typically abnormal program termination. Given this, pointers should be checked to make sure they are valid before they are dereferenced.

Non-Compliant Code Example

In this example, input_str is copied into dynamically allocated memory referenced by str. If malloc() fails, it returns a NULL null pointer that is assigned to str. When str is dereferenced in strcpy(), the program behaves in an unpredictable manner.

Code Block
bgColor#FFCCCC
/* ... */
size_t size = strlen(input_str);
if (size == SIZE_MAX) { /* test for limit of size_t */
  /* Handle Error */
}
str = malloc(size+1);
strcpy(str, input_str);
/* ... */
free(str);

Wiki Markup
NoteIn that in accordance with rule \[[MEM35-C. Allocate sufficient memory for an object]\] the argument supplied to {{malloc()}} is checked to ensure a numeric overflow does not occur.  In most cases it is preferable to check that this value does not exceed some maximum allocation that is typically much smaller than {{SIZE_MAX}}.

Compliant Solution

Wiki Markup
To correct this error, ensure the pointer returned by {{malloc()}} is not NULLnull. InThis additionalso to this rule, this should be done in accordance with rule ensures compilance with \[[MEM32-C. Detect and handle critical memory allocation errors]\].

...

Wiki Markup
Dereferencing an invalid pointer results in undefined behavior, typically abnormal program termination.  In some situations, however, dereferencing a NULLnull pointer can lead to the execution of arbitrary code \[[van Sprundel 06|AA. C References#van Sprundel 06], [Jack 07|AA. C References#Jack 07]\].  The indicated severity is for this more severe case; on platforms where it is not possible to exploit a NULLnull pointer dereference to execute arbitrary code the actual severity is low.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP34-C

3 (high)

3 (likely)

2 (medium)

P18

L1

Automated Detection

Coverity Prevent The Coverity Prevent CHECKED_RETURN, NULL_RETURNS, and REVERSE_INULL checkers can all find violations of this rule. The CHECKED_RETURN finds instances where a pointer is checked against NULL, and then later dereferenced. The NULL_RETURNS checker identifies function that can return a NULL null pointer but are not checked. The REVERSE_INULL identifies code that dereferences a pointer and then checks the pointer against NULL. Coverity Prevent cannot discover all violations of this rule so further verification is necessary.

...