0

i have this struct that is in theory 14 bytes

typedef struct ActionArgument{
 ManagedObjectId managed_object; 
 uint32_t scope1;                        
 OIDType action_type;            
 uint16_t length; } ActionArgument;

the struct ManagedObjectId is 6 bytes , scope is "suposedly" 4 bytes , OIDType is a uint16_t ( 2 bytes ) so is length. But the problem is when i print the size of scope i get 4 bytes which is right , but the size of struct ActionArgument becomes 16. I tried to correct this by spliting scope to 2 uint16_t variables (scope1 and scope2) and it worked . But i am still intrigued why the size of a uint23_t is 4 but when i put it in a struct it becomes 6? can some one explain to me ?

I am using kalilinux 4.14.0-kali3-amd64

thanks.

Dest
  • 11
  • 2

1 Answers1

1

The variables are aligned in memory, so there is a padding added between ManagedObjectId and scope1. One easy way to avoid the padding is to change the struct member order.

ypnos
  • 50,202
  • 14
  • 95
  • 141
  • when i looked in the memory ,the 2 bytes padding are found between scope and action_type – Dest Jan 19 '20 at 15:54
  • Also i can't change the struct member order because it is a message that needs to be transmitted through UDP as is – Dest Jan 19 '20 at 15:55
  • 1
    @Dest `#pragma pack` may be what you are looking for. – Jesper Juhl Jan 19 '20 at 16:03
  • @Dest If you don't want to rely on compiler extensions, you'll have to manually put information into an array of bytes. The structure in memory of `structs` is not guaranteed. The endianess of the system will also affect the message. – Thomas Jager Jan 19 '20 at 16:34
  • thanks @Jesper Juhl , it was a padding problem made by the compiler , #pragma pack(1) just corrected it .Thanks again – Dest Jan 20 '20 at 17:33