Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 10 Mar 1998 14:47:59 -0600 (CST)
From:      Dave Bodenstab <imdave@mcs.net>
To:        grobin@accessv.com
Cc:        questions@FreeBSD.ORG
Subject:   Re: sizeof(struct whatever) doesn't add up
Message-ID:  <199803102047.OAA09850@base486.home.org>

next in thread | raw e-mail | index | archive | help
> From: Geoffrey Robinson <grobin@accessv.com>
>
> I've started working on a CGI in C that uses large structures (over 1kb)
> to hold statistics. I've noticed in previous projects that when I
> attempt to get the size of a structured variable the value sizeof()
> returns is usually a few bytes more than the sum I get if I manually add
> up the sizes of the structure members. Since it worked anyway I passed
> the extra bytes off as something that C needed to keep track of the
> structure. But now that I'm using much bigger structures the extra bytes
> account for as much as 50% of one of my structures. There is no mention
> of anything like this in my C text. What are those extra bytes and, if
> possible, how do I get rid of them? 

Each CPU has differing requirements for accessing various types
of data from memory.  Some CPU's, for instance, requre that a
32-bit quantity be aligned on a 4-byte boundry in memory.  Sometimes,
even tho it's not required, an execution time penalty occurs when
data is not on the proper alignement boundry.

For the Intel x86 CPU's, there is no *requirement* that data be
aligned, but there *is* a performance penalty -- programs run
slower.  So, GCC (the C compiler) makes sure that data is aligned
on the proper boundry to avoid this penalty.

So, if you declare a structure such as:

  struct bad
    {
      char a;
      long b;
      char c;
      long d;
    };

the memory occupied by that structure will be:

  a - 1 byte, offset 0
    - 3 bytes padding
  b - 4 bytes, offset 4
  c - 1 byte, offset 8
    - 3 bytes padding
  d - 4 bytes, offset 12

The sum of the sizes of the individual data items is 10, but sizeof(struct bad)
will be 16.  

A general way to minimize the padding is to order the items from largest
to smallest.  So, if you declared:

  struct good
    {
      long b;
      long d;
      char a;
      char c;
    };

then sizeof(struct good) would be 12.  The extra 2 bytes are padding at
the end of the structure so that each element of an array would still
be aligned properly:

  struct good array[10];

  sizeof(struct good) = 12
  sizeof(array[0]) = 12
  sizeof(array) = 120

A good C textbook should discuss this topic.

Dave Bodenstab
imdave@mcs.net


To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?199803102047.OAA09850>