Reputation: 575
I have the following structure . Where the size is calculated on the side. The size of the structure should be 30Bytes after padding . But the size is 28 . How is the structure size 28?
#include <stdio.h>
struct a
{
char t; //1 byte+7 padding byte Total = 8bytes
double d; //8 bytes Total = 16bytes
short s; //2 bytes Total = 18Bytes
char arr[12];//12 bytes 8+8+4+12=32. Total = 30Bytes
};
int main(void)
{
printf("%d",sizeof(struct a)); // O/p = 28bytes
return 0;
}
Upvotes: 3
Views: 3332
Reputation: 49
In this case for each structure member, memory is given in multiples of 4bytes,
char t - 4bytes, double d - 8bytes, short s - 4bytes and char arr[12] - 12bytes.
total 4(char)+8(double)+4(short)+12(char array)=28bytes
Upvotes: 1
Reputation: 215627
I suspect you're building on a 32-bit architecture where double
does not have 8-byte alignment requirement, in which case the alignments become:
struct a
{
char t; //1 byte+3 padding byte Total = 4bytes
double d; //8 bytes Total = 12bytes
short s; //2 bytes Total = 14Bytes
char arr[12];//12 bytes +2 padding bytes Total = 28Bytes
};
Upvotes: 2
Reputation: 145919
You can use offsetof
to know the actual padding after each structure member:
#include <stddef.h>
printf("Padding after t: %zu\n",
offsetof(struct a, d) - sizeof (((struct a *) 0)->t));
printf("Padding after d: %zu\n",
offsetof(struct a, s) - offsetof(struct a, d)
- sizeof (((struct a *) 0)->d));
printf("Padding after s: %zu\n",
offsetof(struct a, arr) - offsetof(struct a, s)
- sizeof (((struct a *) 0)->s));
printf("Padding after arr: %zu\n",
sizeof(struct a) - offsetof(struct a, arr)
- sizeof (((struct a *) 0)->arr));
As R.
wrote, you are probably on a 32-bit
system where alignment of double
is 4 bytes instead of 8.
Upvotes: 6
Reputation: 515
You are miscalculating the byte padding. This thing depends upon the compiler options and other stuff. You should look into the pragma's pack directive to show you the correct value of padding. For instance:
#pragma pack(show)
should show you the byte padding via the means of a warning. You can also set it explicitly to tailor your code to your needs. Look it up on the msdn. Here is the link http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.71%29.aspx
Upvotes: 4
Reputation: 62123
I think it's aligning on 32-bit boundaries, not 64. How about this:
struct a
{
char t; //1 byte+3 padding bytes Total = 4bytes
double d; //8 bytes Total = 12bytes
short s; //2 bytes+2 padding bytes Total = 16Bytes
char arr[12];//12 bytes 4+8+4+12=28. Total = 28Bytes
};
Upvotes: 2
Reputation: 67852
Most likely, the char is followed by 3 bytes padding (so the double starts on a 4-byte boundary), and the short is followed by 2 bytes padding as well.
But ... why not print the member offsets to see for yourself?
Upvotes: 0