'Twincat 3 - SizeOf returning wrong structure size

I have a structure, and am trying to get the size of this structure. SizeOf returns 16, but I am expecting 14 as answer.

2+2+4+2+2+2=14

By using pointers I noticed that there are 2 empty bytes at the end of the structure.

If I replace the UDINT with UINT then the size is correct. If I put the UDINT at the end of the structure, then the two empty bytes are placed after iCrateCnt.

This leads me to believe that the sizeOf is working properly, but for some unknown reason there are two additional bytes placed somewhere in my structure that I am not using.

Why is this happening and how can it be solved?

enter image description here



Solution 1:[1]

The pack_mode attribute can be used to eliminate unused bytes in a structure.

https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_plc_intro/2529746059.html&id=3686945105176987925

Solution 2:[2]

The unexpected size returned by SIZEOF() are due to so called 'padding bytes'. Where these padding bytes occur depends on:

  1. The system that is used (Tc2 x86, Tc2 ARM, Tc3)
  2. The data types that are used
  3. The order in which these datatypes (c.q. variables) are defined

For more information about padding bytes see Alignment and Structures

As Kolyur has rightfully mentioned the attribute Pack_Mode can be used to control these padding bytes.

For example in Tc3:

TYPE HMI_POPUPSTRUCT : // The total size of this struct is 8 bytes
STRUCT
    bVar1: BOOL;       // At byte 0. 
                       // At byte 1 there will be a padding byte 
    bVar2: INT;        // At byte 2 and 3
    bVar3: BOOL;       // At byte 4     
    bVar4: BOOL;       // At byte 5
    bVar5: BOOL;       // At byte 6.
                       // At byte 7 there will be a padding byte (8th byte)
END_STRUCT

When inserting either

{attribute 'pack_mode' := '0'}

or

{attribute 'pack_mode' := '1'}

just above the struct then there won't be any padding bytes resulting in a struct-size of 6 bytes instead of 8.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kolyur
Solution 2 rick