Re: Packed/padded structs and pointer arithmetic

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

 



On 04/07/2007 02:44 PM, John Anthony Kazos Jr. wrote:

I am seeing things like this quite often in kernel code.

p = (struct partition *) (data + 0x1be);

But isn't it the case that structures by default can have padding for alignment, which can even be different between architectures?

Yes. However, that's not a problem in the above. "data" I assume is a (signed/unsigned) char *, meaning that "data + 0x1be" is just "0x1be bytes into data".

The data at that location is then treated as a struct partition, and if we look at struct partition, it has an __attribute__((packed)) attached; ie, it's specifically telling the compiler to not padd it out.

So for example...

struct foo {
	short int quux;
	short int quuux;
} ;

...could be actually eight bytes long, and doing this...

Absolutely, although it generally won't; it's usually only useful to align fields to their size, meaning the compiler wouldn't be padding anything on x86 for this example.

struct foo {
	short int quux;
	long int quuux;
}

on the other hand _will_ generally turn out as 8 bytes, and not 6; an x86 compiler could (would) be aligning the long to a 4-byte boundary.

struct foo {
	short int quux;
	long int quuux;
} __attribute__((packed));

on the other hand will yield sizeof(struct foo) == 6 again.

Rene.

--
To unsubscribe from this list: send an email with
"unsubscribe kernelnewbies" to ecartis@xxxxxxxxxxxx
Please read the FAQ at http://kernelnewbies.org/FAQ


[Index of Archives]     [Newbies FAQ]     [Linux Kernel Mentors]     [Linux Kernel Development]     [IETF Annouce]     [Git]     [Networking]     [Security]     [Bugtraq]     [Yosemite]     [MIPS Linux]     [ARM Linux]     [Linux RAID]     [Linux SCSI]     [Linux ACPI]
  Powered by Linux