SA0039: Possible null pointer dereferences

Function

Determines code positions at which a NULL-pointer may be dereferenced.

Reason

A pointer should be checked before each dereferencing to see if it is not equal to 0. Otherwise, access violations may occur at runtime.

Importance

High

Sample 1:

PROGRAM MAIN 
VAR
    pInt1     : POINTER TO INT;
    pInt2     : POINTER TO INT;
    pInt3     : POINTER TO INT;
    nVar1     : INT;
    nCounter  : INT;
END_VAR
nCounter := nCounter + INT#1;
 
pInt1    := ADR(nVar1);
pInt1^   := nCounter;            // no error
 
pInt2^   := nCounter;            // => SA0039
nVar1    := pInt3^;              // => SA0039

Sample 2:

FUNCTION_BLOCK FB_Test
VAR_INPUT
    pStruct    : POINTER TO ST_Test;
    refStruct  : REFERENCE TO ST_Test;
END_VAR
VAR
    bPointer   : BOOL := pStruct^.bTest;  // => SA0124: Dereference access in initialization
    bRef       : BOOL := refStruct.bTest; // => SA0125: Reference used in initialization
END_VAR
bPointer := pStruct^.bTest;               // => SA0039: Possible null pointer dereference 'pStruct^'
bRef     := refStruct.bTest;              // => SA0145: Possible use of not initialized reference 'refStruct'
 
IF pStruct <> 0 THEN
    bPointer := pStruct^.bTest;           // no error SA0039 as the pointer is checked for unequal 0
END_IF

IF __ISVALIDREF(refStruct) THEN
    bRef     := refStruct.bTest;          // no error SA0145 as the reference is checked via __ISVALIDREF
END_IF

Overview of the rules on "dereferencing"

Pointer

Dereferencing of pointers in the declaration part

SA0124: Dereference access in initializations

Possible null pointer dereferences in the implementation part

SA0039: Possible null pointer dereferences

References

Use of references in the declaration part

SA0125: References in initializations

Possible use of not initialized reference in the implementation part

SA0145: Possible use of not initialized references

Interfaces

Possible use of not initialized interface in the implementation part

SA0046: Possible use of not initialized interfaces