Sierra Sierra - 4 months ago 16
C Question

struct order with ReadFile

Consider this program:

#include <stdint.h>
#include <stdio.h>
#include <windows.h>
struct os {
uint32_t pa;
char qu[506];
uint16_t ro;
};
int main() {
HANDLE si = CreateFile("\\\\.\\F:", GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
struct os ta;
DWORD un;
ReadFile(si, &ta, 512, &un, NULL);
printf("%x\n", ta.ro);
}


It gives expected output:

> program
aa55


However if I reverse these two lines:

uint32_t pa;
char qu[506];


It gives unexpected output:

> program
0


I have not changed the size of the struct, only the order, so why is it giving
different output, and how do I resolve it?

Answer

This can be resolved by packing the struct:

#pragma pack(1)
struct os {
  char qu[506];
  uint32_t pa;
  uint16_t ro;
};

Example

Another option is:

struct os {
  char qu[506];
  uint32_t pa;
  uint16_t ro;
} __attribute__((__packed__));

However attribute packed is broken on mingw32 compilers.

Comments