[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Programming question: sizeof struct?



Hello Joop.

The compiler is aligning the structure to get faster memoryoperations.
I tried the below structure, and I get it to be 8 bytes.

First the 3 characters which are normal bytes, then the "int" is 4 bytes
long.
Miscalculation? No, it appends a "invisible" byte at the end of the
structure to get it 4-byte-aligned.
If I set the characterarray to 4 bytes, I will still get 8 bytes since
the structure is 4-byte-aligned and the compiler don't need to add an
extra byte.

This is at the low-level of the compiler, assembler I guess.
In the world of 68k-machines a 32-bit type is called "longword" and the
processor can handle handle these 32 bits in a single operation, so
instead if moving 8 bits four times in memory it does it in one 32bit
move.
Intel x86 are almost the same AFAIK.

I suck on describing, but briefly the compiler aligns the data and code
to get some speed in memory-operations like copying/moving/re-arranging.
(humm.. I'm repeating myself.. bah..)

I think there are no way to get a odd-sized structure, but I'm not 101%
sure.

Since I don't know more about what you are actually trying to do in your
code, I can't find any workaround.

Regards...
		Andreas


Joop Stakenborg wrote:
> 
> 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.
> For instance, if the structure were:
> 
> struct foo {
>     char text[3];
>     int  num;
> };
> 
> sizeof would return 6 and not 5.  So it's obvious that the compiler is
> placing a pad byte between text and num to align num.  I want it to
> stop!
> -----------------------------------------------------------------------
> 
> Thanks for your attention.
> 
> Joop
> --
> 
>  Joop Stakenborg PA4TU, ex-PA3ABA <pa3aba@debian.org>
>  Linux Hamradio Applications and Utilities Homepage
>  http://www.casema.net/~aba
> 
> --


Reply to: