Reputation: 10154
I have a struct with 9 bytes worth of members. The sizeof() of the struct is returned as 10. I assume the extra byte is due to padding. Will the padded byte ever be allowed to be used for anything, or does the compiler "reserve" it? i.e. is that memory forever lost as far as the program is concerned?
The reason for asking is I am very short of space so I have used one of the members for storage of several values in one byte using bit manipulation. However, if the padded byte is never otherwise used I can reduce complexity of accessing at least one of the values in the bit manipulated byte by having an extra byte value in place of the padded byte without increasing the overall size of the struct. But if possible I would rather reclaim the padded space to use for other variables. Ta.
typedef struct node {
struct node * sibling, *child; // 2 * 2 bytes
char * name; // 2 bytes
handle callback; // 2 bytes
uint16_t properties; // 1 byte
} node; // total by members = 9 bytes
totalSizeOfnode = sizeof(node); //totalSizeOfNode = 10
Upvotes: 1
Views: 761
Reputation: 39530
The padding space is always going to be available in the future, if you change the structure so that the padding is no longer required or is now occupied by a suitably-sized member.
If you think about the way a compiler works, there is no way that this space could be 'lost forever', because the compiler has no memory of how the source code used to be - it only knows how it is now.
Upvotes: 1
Reputation: 6667
The answer to your question is no, it won't be used. The members of a struct are generally aligned to best suit the underlying architecture it is running on.
On the other hand, most compilers will have to option to control this packing, so if you are short of memory you can tell the compiler to pack the struct members on a byte boundary. Note that this can potentially reduce performance because the CPU may need to do multiple reads to get members that are crossing word boundaries.
Upvotes: 4