C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?

Hybrid View

  1. #1
    Join Date
    Oct 2002
    Location
    Singapore
    Posts
    3,128

    C++ Structure: Why returns 'sizeof()' a bigger size than the members actually need?

    Q: Why returns 'sizeof()' a bigger size than the members actually need?

    A: This is due to structure alignment which aligns the data structure by padding extra bytes so as to optimize for data transfer.

    Modern CPUs perform best in data transfer when fundamental types, such as 'int' and 'float', are stored in memory addresses that are multiples of their length. Some CPUs, like x86, also allow unaligned access but at a performance penalty. In other words, it requires extra data transfer when the data is unaligned.

    When a C/C++ compiler processes a structure declaration, it adds extra bytes between fields to ensure that they are properly aligned. It also adds extra bytes to the end of the structure so that every element of an array of that structure type, is properly aligned.

    As a rule of thumb, to minimize the extra padded bytes needed for the alignment, all fields of the same type should be grouped together. See the following example:

    Code:
    struct MyStructA
    {
        char a;
        char b;
        int c;
    };
    
    struct MyStructB
    {
        char a;
        int c;
        char b;
    };
    
    // Results from VC6 on x86, it may varies for other CPU/OS/compiler combination.
    int sizeA = sizeof(MyStructA);   // sizeA = 1 + 1 + (2-padding) + 4 = 8
    int sizeB = sizeof(MyStructB);   // sizeB = 1 + (3-padding) + 4 + 1 + (3-padding) = 12
    As the C/C++ standard states, the alignment is completely implementation defined, thus, each CPU/OS/compiler combination is free to choose whatever alignment and padding rules it deems best. Although the standard didn't provide any control in customizing the alignment and padding rules, many compilers provide this through non-standard extensions. For example, VC6 provides the pragma pack(n) macro.


    Last edited by Andreas Masur; July 24th, 2005 at 05:06 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center