Reputation: 11
#include <stdio.h>
struct node
{
unsigned color : 2;
};
void main()
{
struct node n;
n.color = 1;
printf("size is :%d\n", (int)sizeof(n));
}
How does the compiler allocate memory for this type of allocation?
The printf gives the output as size is :4
Upvotes: 0
Views: 1177
Reputation: 2534
A member of a structure or union may have any complete object type other than a variably modified type.In addition, a member may be declared to consist of a specified number of bits (including a sign bit, if any). Such a member is called a bit-field its width is preceded by a colon
An implementation may allocate any addressable storage unit large enough to hold a bit- field. If enough space remains, a bit-field that immediately follows another bit-field in a structure shall be packed into adjacent bits of the same unit. If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined. The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined. The alignment of the addressable storage unit is unspecified.
Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.
——ISO/IEC 9899:201x 6.7.2.1
When sizeof is applied to an operand that has type char,unsigned char,or signed char, (or a qualified version thereof) the result is 1. When applied to an operand that has array type, the result is the total number of bytes in the array.103)When applied to an operand that has structure or union type, the result is the total number of bytes in such an object, ncluding internal and trailing padding
——ISO/IEC 9899:201x 6.5.3.4.4
Upvotes: 0
Reputation: 40
The compiler often allocate some empty space between two members of a structure to make the accessing the each member faster. This is called padding. The size of alignment is mostly dependent in processor architecture.
struct data_struct
{
char a;
int b;
};
If we get the size of the structure using sizeof operator on i386, it will come to 8. But the sizeof(char) is one and sizeof(int) is 4 so total of 5 bytes are required but the compiler allocated 8 bytes. Actually it allocated 4 bytes for the char member too.
Upvotes: 2
Reputation: 97918
It allocates sufficient space to store the type specified in the bit-field declaration without considering the number of bits. In your case, unsigned integer size is 4 bytes.
Upvotes: 0
Reputation: 8449
The compiler pads out the struct for alignment. This is not portable as it depends on the architecture of the machine.
Upvotes: 1