I have two source files I am linking:
src1.c:
#include <stdio.h>
typedef struct my_struct {
char a;
short b;
int c;
} my_struct;
my_struct x;
void add1();
int main()
{
x.a = 0;
x.b = 0;
x.c = 0;
add1();
printf("%x, %x, %x\n", x.a, x.b, x.c);
}
and src2.c:
#include <stdio.h>
typedef struct my_struct {
int c;
short b;
char a;
} my_struct;
extern my_struct x;
void add1(){
x.a += 1;
x.b += 1;
x.c += 1;
}
The output is "1, 0, 10001" due to the nature of the type definitions and alignment. However, this rel开发者_C百科ies on the second byte of the struct to be 0x00 (which is a padding byte in the struct for src1.c).
Is this guaranteed behavior? Are padding bytes typically initialized to 0? Are there cases when they wouldn't be?
The two struct types in each source file are not compatible with each other because the members aren't declared in the same order.
This means that my_struct x;
and extern my_struct x;
are not compatible, so you trigger undefined behavior, which loosely speaking means there are no guarantees at all what your program will do.
精彩评论