size of C structure - c

struct st1{
int a:1; int b:3; int c:6; int d:3;
}s1;
struct st2{
char a:3;
}s2;
int main(){
printf("%d : %d",sizeof(s1),sizeof(s2));
getchar();
}
I am getting the output as 2 : 1
will you please tell me, how this program works and whats the use of : operator (a:1) here.
Thank you

The : defines a bit-field.
In your example, objects of type struct st1 use 13 bits in some arrangement chosen by the compiler.
The particular arrangement chosen when you compiled the code originated an object that occupies 2 bytes. The 13 bits are not necessarily the first (or last) in those bytes.
The other struct type (struct st2) occupies (3 bits out of) 1 byte.

The : operator used there specifies sizes in bits of the fields contained there. sizeof() return byte boundary length, so for the first, 13 bits (2 bytes), and for the second, 1 byte.

There's at least two things worth noting here:
Every object must be addressable, which means it will at least occupy the size of one char.
The implementation is free to add padding for alignment or other issues as it sees fit. Iow, a struct containing two ints is not guaranteed to be equal in size to sizeof(int)*2.

Related

When do structures not have padding? [duplicate]

This question already has answers here:
Size of struct containing double field
(5 answers)
Why padding are added, if char comes after int?
(4 answers)
Closed 4 years ago.
sizeof(x) returns 2 for the structure below
struct s {
short c;
} x;
but for the structure
struct s {
short c;
char a;
} x;
sizeof(x) returns 4, Why?
The second one gets one padding byte (assuming short is 2 bytes long and char 1 byte long). Shouldn't the first structure have 2 padding bytes then (and thus be 4 bytes long)?
The predominant use of padding is to align structure members as required by the hardware (or other aspects of the C implementation). An algorithm for laying out data in a struct is in this answer.
To answer the question in your title, when do structures not have padding: A structure does not require padding for alignment if each member’s alignment requirement is a divisor of the total size of all preceding members and of the total size of all members. (A C implementation may still add padding for reasons other than alignment, but that is a bit unusual.)
For your examples, let’s suppose, in a C implementation, short is two bytes in size and requires two-byte alignment. By definition, char is one byte and requires one-byte alignment.
Then, in struct s {short c;}:
c is put at the beginning of the struct. There is never any padding at the beginning.
If we make an array of these struct, the next struct s will begin two bytes beyond the first, and its member c will still be at a multiple of two bytes, so it is aligned correctly.
Therefore, we do not need any padding to make this work.
In contrast, in struct s {short c; char a;}:
c is put at the beginning.
a is put two bytes after c. This is fine, since a only requires one-byte alignment.
If we do not add any padding, the size of the struct is three bytes. Then, if we make an array of these struct, the next struct s will begin three bytes from the start.
In that second struct s, the c member will be at an offset of three bytes. That violates the alignment requirement for short.
Therefore, to make this struct work, we must add one byte of padding. This makes the total size four bytes. Then, in an array of these struct, all the members will be at boundaries required by their alignment.
Even if you declare just a single object of a structure, as in struct s {short c; char a;} x;, a structure is always laid out so it can be used in an array.
The first structure has one element of size 2 (assuming short has size 2 on your system). It is as good as directly having an array of short directly.
The second structure is a special thing: access to short variables is best done on even addresses. If we hadn't padding, we had the following:
struct s arr[5]; // an array
void * a = arr; // needed to reference it
Then,
arr[0].c is at a.
arr[0].a is at a + 2 bytes.
arr[1].c is at a + 3 bytes (!).
arr[1].a is at a + 5 bytes (!).
As it is preferrable to have arr[1].c at an even address, we add padding. Then,
arr[1].c is at a + 4 bytes.
arr[1].a is at a + 6 bytes.

Understanding Structure Padding in C

I understand by data alignment concept that int's and floats's should be stored at address which is divisible by 4 (the starting byte address) .According to it, the size of the below structure is 12
typedef struct{
char A;
int B;
float C;
}y;
I have no doubt in understanding the size of above structure
Now my doubt is about the size of below structure
typedef struct {
double A;
char B;
char C;
}x;
the size of x is 16. what my doubt is that the two characters used can be allocated in 2 bytes such that a whole structure uses 10 bytes of data
and the remaining 2 bytes can be used to allocate to another short int when it was declared right?
But the compiler uses 16 bytes of data and pads the other 6 cells. I can't understand why it is wasting another 6 cells if it can use them for another variables when they are declared?. Can anyone please help me in understanding the above concept?.(I am assuming the size of int ,float and double as 4,4,8 bytes respectively. )
In the case of x, it contains a double which (in your case) has size 8. That means that the structure as a whole needs to be a multiple of that size in order for an array of x to be properly aligned.
Since arrays are contiguously allocated, each member of the array comes immediately after the prior one in memory. If x had size 10, then for an array the second element would have the A member at offset 10. For proper alignment, each array member needs to start at a multiple of the size of the largest element. So the structure contains padding at the end to accomplish this.

Size of the structure assuming that padding is enabled

Assume that i have a structure which is defined as shown below:
typedef struct
{
char a;
int b;
char c;
}abc_t;
Now as per the rules of padding, character variable could start at any address since it has only a single byte while intger variable should start at an address which is divisible by 4 while short variable should start at any even address.
in that case if we assume that character variable starts at OFFSET 0.
struct
{
char a; // OFFSET 0+3 bytes padding
int b; // OFFSET 4
char c; //OFFSET 5+3 bytes padding
}abc_t;
Here the total size of structure would become 12.
But my doubt is if the first element of a structure which is 'char a' here starts at an offset 1 , then based on the rules of padding, we would have only 2 bytes padded after a and hence the size of structure would be 8 bytes.
struct
{
char a;//OFFSET 1+2 bytes
int b;//OFFSET 4
char c;//OFFSET 8
}abc_t;
Same would be the case of any structure variable which would start with short variables.
Can you please tell me if my understanding regarding this is correct or can we safely assume that first member of any structure would always start at an address which is divisible by 4?
Thanks a lot in advance.
There are a few issues here:
1) Size of int is not necessary 4 bytes, its sizeof(int) which is compiler defined. Can be 4 bytes, 8 bytes or even 2 bytes depending on word length. See Is the size of C "int" 2 bytes or 4 bytes?.
2) Field alignment in a struct is up to the compiler. The order in which you put the fields doesn't guarantee tighter packing. The order of fields is preserved, however. See Why isn't sizeof for a struct equal to the sum of sizeof of each member?.
3) Putting shorter structs together would USUALLY cause tighter packing.
4) Structs begin at word boundaries. There is never any padding before the first field. So yes, the address would be at the beginning of a word. Why use address of first element of struct, rather than struct itself?.
Hope this helps.

Why padding are added, if char comes after int?

For example, there is a structure
struct A
{
char a;
int i;
};
In this case, we have a[1 byte] + padding[3 byte] + int[4 byte] = 8.
Now let's make little update into struct above,
struct A
{
int i;
char a;
};
In this case char comes after int and no need to add padding bytes, it means sizeof(A) = 5 byte, but in this case I also get the 8 byte result. Why ?
Ok, and what about this case
struct s
{
int b;
double c;
char a;
};
According logic given below, there is a: size = b[4 bytes] + padding[4 bytes] + c[8] + a[1] + padding[7 bytes to align with double] = 24,
but after execution I get 16. How this is possible ?
In this case char comes after int and no need to add padding bytes, it means sizeof(A) = 5 byte, but in this case I also get the 8 byte result. Why ?
First you need to understand why padding is needed?
Wiki says that:
Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding. When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system) or larger. Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.
To make the size multiple of 4 (alignment of int) , the second snippet will be padded with 3 bytes. After compilation the second snippet will be padded for proper alignment as
struct A
{
int i;
char a;
char Padding[3]; // 3 bytes to make total size of the structure 8 bytes
};
EDIT: Always remember these two golden rules of structure padding:
Padding is only inserted when a structure member is followed by a member with a larger alignment requirement or at the end of the structure.
The last member is padded with the number of bytes required so that the total size of the structure should be a multiple of the largest alignment of any structure member.
In case of
struct s
{
int b;
double c;
char a;
};
alignment will take place as
struct s
{
int b; // 4 bytes. b is followed by a member with larger alignment.
char Padding1[4]; // 4 bytes of padding is needed
double c; // 8 bytes
char d; // 1 byte. Last member of struct.
char Padding2[7]; // 7 bytes to make total size of the structure 24 bytes
};
Also note that by changing the ordering of members in a structure, it is possible to change the amount of padding required to maintain alignment. This can be done by if members are sorted by descending alignment requirements.
struct s
{
double c; // 8 bytes
int b; // 4 bytes
char a; // 1 byte. Only last member will be padded to give structure of size 16
};
The reason the compiler have to add padding at the end of your struct is that the struct can be part of an array, and each element of an array must be properly aligned.
It seems your platform wants an int to be aligned to 4 bytes.
If you declare an array of your struct A:
struct A array[2];
Then the first int member of array[1] should also have an alignment of 4 bytes. So the compiler pads your struct A to be 8 bytes to accomplish that, whilst if it didn't add any padding and sizeof(struct A) were 5 bytes, array[1] would not be properly aligned.
(Keep in mind that a compiler can't insert padding inbetween array elements, padding have to be part of the array elements themselves since sizeof array must be the same as sizeof(struct A) * 2 in the above case)
Not only each member of the struct has to be data aligned, but the struct itself has to aligned to the size of the largest member in the struct. So, padding is added to struct A such that its size should be a multiple of the larger of sizeof i and sizeof a.
Have a look at C FAQ here
If one is going to have an array of structures, all elements within the array must have the same size and alignment; this would imply that for things in an array the size must be a multiple of alignment. The only time it would be useful to have a structure whose size was not a multiple of alignment would be if it was not incorporated directly into another array, but was instead used as part of another structure. That kind of situation does occur sometimes, but not sufficiently often as to merit special attention in the language design.

How is the size of a struct with Bit Fields determined/measured?

#include <stdio.h>
typedef struct size
{
unsigned int a:1;
unsigned int b:31;
unsigned int c:1;
} mystruct;
int main()
{
mystruct a;
printf("%d", sizeof(a));
return 0;
}
With int b:31, the output is 8.
With int b:1, the output is 4.
With int b:32, the output is 12.
Can somebody explain the reason for this?
It is the order that matters. The following code will give Output: 8
#include<stdio.h>
typedef struct size
{
unsigned int b:32;
unsigned int a:1;
unsigned int c:1;
}mystruct;
int main(int argc, char const *argv[])
{
mystruct a;
printf("\n %lu \n",sizeof(a));
return 0;
}
Unsigned int is a 32 bit integer, occupying 4 bytes. Memory is allocated contiguously in memory.
Option 1:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:31; // Will get accomodated in the First 4 bytes
unsigned int c:1; // Second 4 bytes are allocated
Output: 8
Option 2:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:32; // Will NOT get accomodated in the First 4 bytes, Second 4 bytes are allocated
unsigned int c:1; // Will NOT get accomodated in the Second 4 bytes, Third 4 bytes are allocated
Output: 12
Option 3:
unsigned int a:1; // First 4 bytes are allocated
unsigned int b:1; // Will get accomodated in the First 4 bytes
unsigned int c:1; // Will get accomodated in the First 4 bytes
Output: 4
Option 4:
unsigned int b:32; // First 4 bytes are allocated
unsigned int a:1; // Second 4 bytes are allocated
unsigned int c:1; // Will get accomodated in the Second 4 bytes
Output: 8
You don't say whether you know what bitfields are, but I'll assume you do.
On your implementation, evidently unsigned int is a 32 bit integer, occupying 4 bytes. This accounts for the first and second examples. Clearly 3 bitfields totalling 33 bits don't fit into a single unsigned int, hence the need for 8 bytes in the first example. 3 bitfields totalling 3 bits certainly do fit into an unsigned int, hence only 4 bytes in the second example.
Furthermore, a bitfield cannot span multiple integers. This accounts for the third example. I can't remember whether that's a requirement of the standard, or just a detail of your implementation. Either way, since b is 32 bits, it fills a whole unsigned int on its own, forcing both of a and c to occupy their own unsigned int, before and after the middle one. Hence, 12 bytes.
According to Steve jessop's answer just to fulfill his answer by adding some documents which may help.
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
Alignment
The compiler is rounding the size of the structure to 32 bits, the size of each object it may try to reference to 32 bits, and at the same time it is preserving the order of your bit fields.
So if you have a 32-bit item in the middle and 1-bit items on each side, that's 3 32-bit words to allocate and so: 12 bytes.
For the other two cases, it's just a question of how few 32-bit objects your bitfield sequence can be packed into, while still preserving field order.

Resources