Re: memory allocation/alignment under linux

From: Roger Leigh (${roger}_at_whinlatter.uklinux.net.invalid)
Date: 01/20/05


Date: Thu, 20 Jan 2005 12:10:07 +0000

On 2005-01-18, puzzlecracker <ironsel2000@gmail.com> wrote:
> Got Confused on the interview with memory alligment questions... PLEASE
> HELP -- How much bytes of memory will structs below take on 32 bit
> machine? What about 64 bit machine? Why is it different? (if it's
> relevent, use standard size of datatypes)

Which Linux? i386, IA-64, amd64, ARM, MIPS, SPARC32/64, PA-RISC, Alpha??
Each will potentially be different.

> Code:
> struct
> {
> short int a;
> int b;
> };

Assuming 32-bit Intel, "short int" is 16-bits, and "int" is 32 bits. We
would expect int to be aligned on a word boundary (4 bytes), giving this
arrangement:

      size running total
-------------------------
a 2 2
[pad] 2 4
b 4 8

To test this, write a simple program which will tell you what really
happens.

#include <stdio.h>
#include <stdint.h>

struct test
{
  short int a;
  int b;
} /* __attribute__ ((packed)) */;

#define SOFFSET(struct_type, member_name) \
  ((unsigned long) ((uint8_t *) &((struct_type*)0)->member_name))

int main(void)
{
  printf("Member a size: %lu\n", (unsigned long) sizeof(short int));
  printf("Member a offset: %lu\n", (unsigned long) SOFFSET(struct test, a));
  printf("Member b size: %lu\n", (unsigned long) sizeof(int));
  printf("Member b offset: %lu\n", (unsigned long) SOFFSET(struct test, b));
  printf("Structure size: %lu\n", (unsigned long) sizeof(struct test));
  return 0;
}

Note that compiler options will also affect structure alignment.
Uncomment the "__attribute__ ((packed))" comment, and recompile.
Notice there is now no padding.

For the other questions, repeat as above. Note that (as any
good C++ text will tell you), if the class contains any
virtual functions, each type instance of the object must contain
a pointer to the class structure (virtual call table), i.e.
one extra pointer.

Regards,
Roger

-- 
Roger Leigh
                Printing on GNU/Linux?  http://gimp-print.sourceforge.net/
                GPG Public Key: 0x25BFB848.  Please sign and encrypt your mail.


Relevant Pages