Null pointer dereference Medium

We observed that a NULL pointer dereference occurs when a program attempts to access the value referenced by a pointer that is currently set to NULL. To address this vulnerability effectively, implement always initialize pointers before use, check for NULL before dereferencing pointers and be cautious when freeing or deallocating memory to avoid using pointers that have been freed.

Detector ID
c/null-pointer-dereference@v1.0
Category
Common Weakness Enumeration (CWE) external icon
Tags
-

Noncompliant example

1#include <stdio.h>
2#include <stdlib.h>
3#include <stddef.h>
4#include <string.h>
5#include <assert.h>
6
7void NullPointerDereferenceNonCompliant()
8{
9    int *ptr;
10    // Noncompliant: Dereferencing uninitialized pointer
11    int value = *ptr;
12}

Compliant example

1#include <stdio.h>
2#include <stdlib.h>
3#include <stddef.h>
4#include <string.h>
5#include <assert.h>
6
7void NullPointerDereferenceCompliant()
8{
9    int *ptr = NULL;
10    // Compliant: Checking for NULL before dereferencing
11    if (ptr != NULL)
12    {
13        int value = *ptr;
14    }
15}