SA0021: Transporting the address of a temporary variable

Function

Determines assignments of addresses of temporary variables (variables on the stack) to non-temporary variables.

Reason

Local variables of a function or method are created on the stack and exist only while the function or method is processed. If a pointer points to such a variable after processing the method or function, then this pointer can be used to access undefined memory or an incorrect variable in another function. This situation must be avoided in any case.

Importance

High

Sample:

Method FB_Sample.SampleMethod:

METHOD SampleMethod : XWORD
VAR
    fVar  : LREAL;
END_VAR
SampleMethod := ADR(fVar);

MAIN program:

PROGRAM MAIN
VAR
    nReturn   : XWORD;
    fbSample  : FB_Sample;
END_VAR
nReturn := fbSample.SampleMethod();                 // => SA0021