Attention
IronPLC implements many parts of the IEC 61131-3 standard and is working toward full Structured Text support. Key features still missing include arrays and structures. Try it out in the IronPLC Playground.
P2029¶
- Code
P2029
- Message
REF() of stack-allocated variable (VAR_TEMP or FUNCTION VAR_INPUT/VAR_OUTPUT) would create a dangling reference
This error occurs when REF() is applied to a stack-allocated variable that would be destroyed when the function returns, creating a dangling reference. Variables in VAR_TEMP sections and VAR_INPUT/VAR_OUTPUT sections of FUNCTION declarations (not FUNCTION_BLOCK) are stack-allocated.
Example¶
The following code will generate error P2029:
FUNCTION MyFunc : INT
VAR_TEMP
temp : INT;
END_VAR
VAR
x : REF_TO INT;
END_VAR
x := REF(temp); (* Error: temp is stack-allocated and will be destroyed *)
END_FUNCTION
To fix this error, use a variable from a persistent scope such as a FUNCTION_BLOCK instance variable:
FUNCTION_BLOCK MyFB
VAR
counter : INT;
x : REF_TO INT;
END_VAR
x := REF(counter); (* Correct: FB instance variables persist *)
END_FUNCTION_BLOCK