Skip to content

Question Regarding Factory Method Pattern and Memory Management in Structured Text #25

@BhanuKiranChaluvadi

Description

@BhanuKiranChaluvadi

I am trying to understand the memory allocation and deallocation process when using the Factory Method design pattern in Structured Text. Specifically, I am confused about how memory is allocated, returned, and subsequently freed in the following skeleton code.

Code Skeleton

INTERFACE I_Shape

{attribute 'enable_dynamic_creation'}
FUNCTION_BLOCK FB_Circle IMPLEMENTS I_Shape

FUNCTION_BLOCK FB_ShapeCreator
VAR_INPUT
    eShape : E_Shape;
END_VAR
VAR
    pCircle    : POINTER TO FB_Circle;
    pRectangle : POINTER TO FB_Rectangle;
    pSquare    : POINTER TO FB_Square;
    pStar      : POINTER TO FB_Star;
    pTriangle  : POINTER TO FB_Triangle;
    iShape     : I_Shape;
END_VAR

METHOD M_GetShapeObject : I_Shape
VAR_INPUT
END_VAR

CASE eShape OF
    E_Shape.Circle:
        // Dynamic instantiation  
        pCircle := __NEW(FB_Circle);
        iShape := pCircle^;
        
        // Return the object
        IF iShape <> 0 THEN
            M_GetShapeObject := iShape;
        END_IF

        // Release the memory
        IF (pCircle <> 0) THEN
            __DELETE(pCircle);
            pCircle := 0;
        END_IF

        eShape := E_Shape.init;
    ...
END_METHOD

Questions & Concerns

  1. Memory Allocation & Return:

    • The statement pCircle := __NEW(FB_Circle); allocates memory on the heap, and pCircle holds the address of the allocated memory.
    • Later, we assign M_GetShapeObject := iShape;, but what exactly is being returned?
      • Is it a copy of the object on the stack being returned to the caller?
      • Or is the function returning a reference to the memory allocated on the heap?
  2. Memory Deallocation Issue:

    • If iShape holds a reference to the heap-allocated memory, it seems problematic that we immediately deallocate the memory with:
      IF (pCircle <> 0) THEN
          __DELETE(pCircle);
          pCircle := 0;
      END_IF
      
    • Would this not result in a situation where M_GetShapeObject is returning a reference to an already freed object?
  3. Clarification on M_GetShapeObject := iShape;:

    • What exactly happens on this line? Is it performing a deep copy of the object or just assigning a reference to the heap-allocated memory?
  4. Further Reading:

    • If there are any official references or online materials explaining how memory management works with __NEW and __DELETE in Structured Text, I would appreciate the guidance.

Thank You!

I appreciate any insights or explanations that can help clarify this behavior.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions