Re: Programming question: sizeof struct?
Joop Stakenborg writes:
> Hi there,
>
> The upstream maintainer of one of my packages is having problems
> with his code. I thought it would be nice to use the debian mailing
> lists, to see if we can an answer on this. I will forward any solution
> to him.
>
> ----------------------------------------------------------------------
> The reason why I have not released LogConv 1.54 for Linux is that I am
> having problems with packed structures that is causing some file formats
> to not be handled properly. Even though I specify -fpack_struct the
> generated code does not appear to actually do this. Structure fields
> are
> offset and the return from sizeof() returns a value that is not valid.
The return value from sizeof _is_ valid. It returns the amount of
memory the object occupies in memory. Maybe you don't like it, but
that is another issue.
> For instance, if the structure were:
>
> struct foo {
> char text[3];
> int num;
> };
>
> sizeof would return 6 and not 5.
Um, I get 8 instead of 7 (an int is usually 4 bytes in linux):
oef.c
------------------------------------------------------------------------
#include <stdio.h>
struct A {
char a[3];
int b;
};
int main(void) {
printf("%u\n", (unsigned) sizeof(struct A));
return 0;
}
------------------------------------------------------------------------
If I compile and run like this:
$ gcc -O2 -o oef oef.c
$ ./oef
8
... I do get padding, and if I compile and run like this:
$ gcc -fpack-struct -O2 -o oef oef.c
$ ./oef
7
... I don't get padding. This is using gcc 2.7.2.3. I can imagine
that there exist optimization options that affect this though,
especially the -malign-... type. Maybe you need to switch these off.
There is a second, very-unportable-too-I-guess way:
oef2.c:
------------------------------------------------------------------------
#include <stdio.h>
struct A {
char a[3];
int b __attribute__ ((packed));
};
int main(void) {
printf("%u\n", (unsigned) sizeof(struct A));
return 0;
}
------------------------------------------------------------------------
This yields:
$ gcc -O2 -o oef2 oef2.c
$ ./oef2
7
However, unless you are really tight on memory, it is a bad idea to muck
around with the default padding in structures, since it degrades
performance. If the issue is to write binary files that are portable
across different architectures, then padding in structures is only one
of the problems you will encounter. Have a look at the C-FAQ-list at
URL: http://www.eskimo.com/~scs/C-faq/top.html, item 20.5, for
references on how to tackle this problem.
HTH,
Eric
--
E.L. Meijer (tgakem@chem.tue.nl)
Eindhoven Univ. of Technology
Lab. for Catalysis and Inorg. Chem. (SKA)
Reply to: