Thread: Doubt regarding structure padding and normal variable

  1. #1
    Registered User
    Join Date
    Jan 2009
    Posts
    53

    Doubt regarding structure padding and normal variable

    In the below structure, lets say

    Code:
    struct add {
    
    int x;
    char y;
    };
    the size of the structure add will be 8 bytes because of structure padding concept that 3 bytes will be padded to the char y. Because, according to my understanding, as the processor will request the memory for words(i.e., 4 bytes) and as char in this structure will have only 1 byte, extra 3 bytes need to be padded.

    But lets say, a normal character variabel is delcared in a program as
    Code:
    int main
    {
        char c = 1; 
        return 0;
    }
    then in the memory for the variable c, only 1 byte will be allocated, then how the processor will request this memory using word...without padding?

  2. #2
    Registered User
    Join Date
    Sep 2012
    Posts
    357
    Because it (probably) puts the variable at an address multiple of 4.
    The Standard makes no requirement about padding; it merely allows padding (in the interest of performance).

  3. #3
    Registered User ledow's Avatar
    Join Date
    Dec 2011
    Posts
    435
    There's nothing to say that it doesn't use padding for that char. And whether it does or not, does not affect the usage of that char or its surrounding variables (only if you do something dumb and undefined like getting a pointer to that char, adding one to it, and expecting it to be the NEXT char that you defined somewhere else, not in a char array. E.g.:
    Code:
    {
        char a;
        char b;
         printf("%c", ++a);   // Don't expect this to print the contents of b.
    }
    will likely crash or just print garbage. Precisely BECAUSE there might be ten miles of padding between a and b, or even that b is stored in memory prior to a!). If you allocate memory for a char, you can end up with allocated memory of 1 byte or 4 bytes but it doesn't matter because the actual char is only ever 1 byte of actual significant data, so it will always fit and reference properly itself.

    With the structure, the padding DOES matter hugely because the whole structure will be a single, continuous block of memory designed to hold several things. If you assume it has no padding, your memory allocations will be completely wrong, and likely too small to hold the whole structure.

    Nobody says that memory padding doesn't happen everywhere in C - hell, I guarantee you that the memory you malloc isn't allocated down to the byte level at all and more likely you got a block of whatever the memory page size is (e.g. 1kb or 4kb). It's just that it doesn't matter so long as you DON'T use more than you requested. With structures it does matter, and you can't assume the elements are ordered, continuous or padding-free, nor guess at the total size of a structure element because you will request too little unless you use sizeof to properly include the padding into your calculations. That's all sizeof's job really is - to tell you things you can NEVER know for sure on the architecture any other way.

    Basically: NEVER make any assumptions about how large ANYTHING will be in memory - always use sizeof. Your guess at anything is unlikely to be right, especially when you move between architectures. Use sizeof, and take note of only the MINIMUM GUARANTEED SIZE of any allocations (e.g. char will always be AT LEAST 1 byte, but that doesn't mean it won't actually be stored as 2048 bytes with unused bytes around it, etc.)

    - Compiler warnings are like "Bridge Out Ahead" warnings. DON'T just ignore them.
    - A compiler error is something SO stupid that the compiler genuinely can't carry on with its job. A compiler warning is the compiler saying "Well, that's bloody stupid but if you WANT to ignore me..." and carrying on.
    - The best debugging tool in the world is a bunch of printf()'s for everything important around the bits you think might be wrong.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    ledow, I assume you intended your printf() line to be
    Code:
        char *p = &a;
        printf("%c", *(++p));   // Don't expect this to print the contents of b.
    More generally, the layout and size of any data type in memory - and whether padding is included or not - is implementation defined.

    And sizeof(char) is always 1. The standard defines that.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  5. #5
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Quote Originally Posted by ledow View Post
    ... or even that b is stored in memory prior to a!).
    I thought something to do with the memory model in the recent standards (both in C++ and C) prevented that.
    <I might be very wrong or have a warped understanding though!>

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by manasij7479 View Post
    I thought something to do with the memory model in the recent standards (both in C++ and C) prevented that.
    <I might be very wrong or have a warped understanding though!>
    There is nothing in the C or C++ standard that prevents such a thing. Any code that relies on any relationship between the locations in memory of two variables (a located before b, b located before a, a adjacent to b) yields undefined behaviour.

    There are some constraints on the ordering of struct members, but not on the spacing between them.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  7. #7
    Registered User
    Join Date
    Mar 2009
    Posts
    344
    Quote Originally Posted by karthik537 View Post
    In the below structure, lets say

    Code:
    struct add {
    
    int x;
    char y;
    };
    the size of the structure add will be 8 bytes because of structure padding concept that 3 bytes will be padded to the char y.
    Or it will be 12 bytes or 16 bytes or maybe 4 bytes, or something totally different. It very rarely matters - and usually then it only matters when you're doing something you shouldn't. When it does matter, as others have said, there are portable ways to get the information rather than trying to outthink the compiler.

    But lets say, a normal character variabel is delcared in a program as
    Code:
    int main
    {
        char c = 1; 
        return 0;
    }
    then in the memory for the variable c, only 1 byte will be allocated, then how the processor will request this memory using word...without padding?
    In your example the code never uses c so it should never make the processor request the memory in the first place. Or maybe the compiler will be smart enough to do the math for you during the compile process so nothing is calculated at run time. Or maybe the value will always be stored in a register and never spilled to memory, meaning it takes up however many bytes a register has but no loads are ever executed. But even if it doesn't apply those optimizations, the compiler is perfectly free to allocate a single byte or an entire cache line or page as it sees fit for the job. Only way to tell is to look at the assembler code and see.

    My point? While it is good to understand the abstract model that C presents for how code works, don't get too attached to thinking you understand what the compiler is actually going to do. Worrying about how the compiler implements this abstract model will generally get you into more trouble than it will save - remember that just because compiler X version Y with settings Q on OS Z does it one way that doesn't mean that every other compiler must. Focus instead on writing good portable code using properly selected algorithms rather than worrying about saving or using an extra byte here or there.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C Structure Padding
    By audinue in forum C Programming
    Replies: 20
    Last Post: 07-12-2011, 10:14 PM
  2. Structure Padding in C
    By karthik537 in forum C Programming
    Replies: 3
    Last Post: 06-15-2011, 07:10 AM
  3. Structure padding
    By ShashiKantSuman in forum C Programming
    Replies: 4
    Last Post: 05-03-2011, 07:50 AM
  4. Structure padding
    By MK27 in forum C Programming
    Replies: 4
    Last Post: 12-15-2009, 02:25 PM
  5. Padding in Structure
    By ganesh bala in forum C Programming
    Replies: 11
    Last Post: 01-29-2009, 09:25 PM