i want to test if it is OK to access a mis-aligned member of a structure in C, please see the code
#include <stdio.h>
#pragma pack(1) /* force 1 byte alignment */
/* either member b or member d is mis-aligned */
typedef struct
{
int b;
unsigned char c;
unsigned int d;
}A ;
int main(int argc, char *argv[])
{
A _a = {0};
unsigned int *p = NULL;
unsigned int *q = NULL;
printf("addr of _a : 0x%08x, size of _a : %u\n", &_a, sizeof(_a));
p = (unsigned int*)(&_a.b);
q = (unsigned int*)(&_a.d);
/* should this fail ? */
(*p)++ , (*q)++;
return 0;
}
assume the program will crash due to an exception caused by the mis-aligned memory access, but it turns out that it works quite well, have tested in Linux 3.6.11(GCC 4.7.2) , WinXP(MingW), codepad online compiler(http://codepad.org/yOoc8ACG)
please explain the result, i guess the OS have done something to save the program, still doubt if it works in VxWorks or some other operating systems
note: the code runs on an Intel-based machine!
thanks in advance !