Re: memory alignment?

Discussion in 'C++' started by Andrew Koenig, Aug 1, 2003.

  1. cylin> If I have a class like below.
    cylin> class test {
    cylin> int a;
    cylin> double b;
    cylin> };

    cylin> Using sizeof(test), it'll get 16 bytes.
    cylin> Because I maybe handle larger than 1 million such kind objects.
    cylin> Can't we reduce this class to only cost 12 bytes?

    In other words, you want to be able to write

    test xyzzy[1000000];

    and have it take up 12 million bytes instead of 16 million.

    Let's assume that an int takes up 4 bytes and a double takes
    up 8 bytes. Then whether you can do what you want depends on
    whether your implementation requires a double to be aligned on
    a 4-byte or an 8-byte multiple.

    However, if it required 4-byte alignment only, then I would have
    expted sizeof(test) to be 12, not 16. It is conceivable, though
    unlikely, that if you rewrote it this way:

    class test {
    double b;
    int a;

    that the compiler would use only 12 bytes for each object. However, I
    would expect any compiler that inserts padding in the first example
    above to insert padding between array elements also.

    So what can you do? If you really need to save the space, you can
    split up the elements of your data structure:

    double b_array[1000000];
    int a_array[1000000];

    and then access the elements individually. Yes, I know that's
    perverting your data structure. As Robert Dewar once told me,
    some programs are poorly designed on purpose.

    Andrew Koenig,
    Andrew Koenig, Aug 1, 2003
    1. Advertisements

  2. Andrew Koenig wrote:
    > As Robert Dewar once told me,
    > some programs are poorly designed on purpose.

    A wise guy.

    Karl Heinz Buchegger
    Karl Heinz Buchegger, Aug 1, 2003
    1. Advertisements

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter van Merkerk

    Re: memory alignment?

    Peter van Merkerk, Aug 1, 2003, in forum: C++
    David Cattarin
    Aug 1, 2003
  2. Thomas Matthews

    Re: memory alignment?

    Thomas Matthews, Aug 1, 2003, in forum: C++
    Thomas Matthews
    Aug 1, 2003
  3. J. Campbell
    Default User
    Oct 9, 2003
  4. Paul_Huang

    Memory Padding and alignment

    Paul_Huang, Sep 21, 2004, in forum: C++
    Serge Paccalin
    Sep 21, 2004
  5. aneesh

    memory alignment

    aneesh, Sep 24, 2003, in forum: C Programming
    Micah Cowan
    Sep 24, 2003

Share This Page