Skip to main content

SA0065: Incorrect pointer addition to base size

Detects pointer additions for which the value to be added does not match the base size of the pointer. Only literals of the base data size and multiples thereof can be added without error.

Justification: In CODESYS (in contrast to C and C++), when adding a pointer with an integer value, only this integer value is added as the number of bytes, and not the integer value multiplied by the base size.

Example 76. Example in ST
pINT := ADR(array_of_int[0]);
pINT := pINT + 2;   //in CODESYS, pINT then points to array_of_int[1]

This code would function differently in C:

short* pShort
pShort = &(array_of_short[0])
pShort = pShort + 2;  //in C, pShort then points to array_of_short[2]


Therefore, in CODESYS, you should always add a multiple of the base size of the pointer to a pointer. Otherwise, the pointer may point to not aligned memory which (depending on the processor) can lead to an alignment exception when accessing it.

Importance: High

Example 77. Example
VAR
    pudiTest:POINTER TO UDINT;
    udiTest:UDINT;
    prTest:POINTER TO REAL;
    rTest:REAL;
END_VAR
pudiTest := ADR(udiTest) + 4;    // OK
pudiTest := ADR(udiTest) + ( 2 + 2 );    // OK
pudiTest := ADR(udiTest) + SIZEOF(UDINT);    // OK
pudiTest := ADR(udiTest) + 3;    // SA0065
pudiTest := ADR(udiTest) + 2*SIZEOF(UDINT);    // OK
pudiTest := ADR(udiTest) + ( 3 + 2 );    // SA0065
prTest := ADR(rTest);
prTest := prTest + 4;    // OK
prTest := prTest + ( 2 + 2 );    // OK
prTest := prTest + SIZEOF(REAL);    // OK
prTest := prTest + 1;    // SA0065
prTest := prTest + 2;    // SA0065
prTest := prTest + 3;    // SA0065
prTest := prTest + ( SIZEOF(REAL) - 1 );    // SA0065
prTest := prTest + ( 1 + 4 );    // SA0065

Output in the Messages view:

  • sa_icon_message.png SA0065: Incorrect pointer addition to base size