Reputation: 21
I am trying the following, with gcc on win32.
#include <stdio.h>
struct st { char c; int x; } __attribute__ ((packed));
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
I would expect that the printed value is 5, but it's 8.
With the following, however, I get 5.
#include <stdio.h>
#pragma pack(1)
struct st { char c; int x; };
int main() {
printf("%d\n", sizeof(struct st));
return 0;
}
There must be something wrong in my program, but I can't see what. I have read gcc's manual and several questions on SO about this, and I'm still puzzled. Any hint?
Also from the answers to these questions on SO, I understand that I should not use packed structs for marshalling, and I probably won't use it much, but I still would like to understand what I'm not able to see in such a short program.
Note: the problem occurs with both gcc-4.9.2 and gcc-4.8.4.
Upvotes: 2
Views: 1595
Reputation: 1664
Working fine on my environment Centos 5.11 (64bit) prints 5 for the first case you mentioned.
gcc version 4.9.1 (GCC)
gcc file.c
./a.out
5
Upvotes: 0
Reputation: 212929
You have the attribute in the wrong place - try this:
struct st { char c;
int x __attribute__ ((packed));
};
As per the example in the gcc manual, this will cause x
to be packed such that it immediately follows c
.
Of course you shouldn't really be doing this in the first place, as your code will break on certain architectures, and even where it doesn't break there may be performance penalties.
Upvotes: 2