Invader Zim Invader Zim - 1 year ago 49
C Question

Struct not stored in memory as expected

I'm working with esp8266, Non-OS SDK.

I'm trying to understand how softap_config structure is stored in memory. The reason for this is that I plan to implement configuring espressif over UDP, and I would rather send the whole struct as it should be, and then just memcpy it.

From user_interface.h:

struct softap_config {
uint8 ssid[32];
uint8 password[64];
uint8 ssid_len; // Note: Recommend to set it according to your ssid
uint8 channel; // Note: support 1 ~ 13
AUTH_MODE authmode; // Note: Don't support AUTH_WEP in softAP mode.
uint8 ssid_hidden; // Note: default 0
uint8 max_connection; // Note: default 4, max 4
uint16 beacon_interval; // Note: support 100 ~ 60000 ms, default 100
};
typedef enum _auth_mode {
AUTH_OPEN = 0,
AUTH_WEP,
AUTH_WPA_PSK,
AUTH_WPA2_PSK,
AUTH_WPA_WPA2_PSK,
AUTH_MAX
} AUTH_MODE;


So, the first thing I did was:

os_printf("size in mem: %d\n", sizeof(struct softap_config));


And I got 108 insted of expected 103.

I then proceeded to printing hex values of:


  1. struct fields or their first member if they are an array

  2. whole structure as an uint8_t array



What I found is:


  1. between channel and authmode there is always [0x2 0x3]

  2. between authmode and ssid_hidden there is always [0x0 0x0 0x0]



It fits perfectly that there are five additional bytes, that explains the size. These bytes stay the same independently of the struct field values, as far as I tested.

But why is it like that? And what could these values mean?
I guess it has something to do with AUTH_MODE?

Answer Source

Your error is two-fold:

  1. You don't force the compiler to use short enums, likely with an option like -fshort-enums, thus it is free to use a "natural" size, like that of an int, in your case 4. Concomittant, the alignment is also 4 instead of 1.
  2. uint16 likely already has an alignment of 2, so even if the enum's size and alignment was 1, the size would be at least 104 unless you use a compiler-specific extension to pack that struct regardless of alignment-constraints.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download