Memory Management

Pointer :

Pointers store the addresses of variables, function blocks and programs, while an application program is running. A pointer points to one of the named objects or to a variable with any data type.

Dereferencing a pointer means obtaining the value of the address to which the pointer points. You can dereference a pointer by appending the content operator to the pointer identifier, for example see pSample^ in the example below.

You can use the address operator ADR to assign the address of a variable to a pointer.

Example:

VAR
    //declaration of pointer pSample
    pSample : POINTER TO INT; // pointer to integer data type, we can declare any type here
    //declaration of variables nVar1 and nVar2
    nVar1 : INT := 5;
    nVar2 : INT;
END_VAR
pSample := ADR(nVar1); //pointer pSample is assigned to address of nVar1 
//value 5 of nVar1 is assigned to variable nVar2 by dereferencing of pointer pSample 
nVar2 := pSample^;  //value of nVar2  will be same as nVar1, if we change nVar2 then nVar1 will be changed as well.


Memcpy

Library contains a number of functions which provide direct access to memory areas in the PLC runtime system of the PLC Controller. Default editor includes the library by default.

 

The fact that these functions allow direct access to the physical memory of the PLC. Misuse of such functions can result in a system crash, or in access to forbidden memory areas. So we need to be careful when we are using these function.

 

MEMCMP Compares the values of variables in two memory areas

 

MEMCPY Copies the values of variables from one memory area to another

 

MEMSET Sets the variables in a memory area to a particular value

Memcpy example

//Declaration

PROGRAM MAIN

VAR

org : DINT :=12;

dest : DINT :=13;

another : DINT := 14;

myTimer : TON;

startTimer : BOOL := FALSE;

END_VAR

//Body

 

myTimer(IN:= startTimer, PT:=T#1S);

 

MEMCPY(ADR(dest), ADR(org),4);

MEMCPY(ADR(another), ADR(dest),4);

 

IF myTimer.Q = TRUE THEN

myTimer(IN:= FALSE);

org:= org +1;

END_IF