Let's have a look at the following program and the output
bpte4500s001:/sunbuild1/giri/testcases/%cat aligndata.c
#include <stdio.h>
typedef struct user {
char name[10];
int age;
float salary;
} usr;
int main()
{
printf("\n ** sizeof(char) = %d, sizeof(int) = %d, sizeof(float) = %d\n ** sizeof(struct user) = %d\n", sizeof(char), sizeof(int), sizeof(float), sizeof(struct user));
return (0);
}
bpte4500s001:/sunbuild1/giri/testcases/%./a.out
** sizeof(char) = 1, sizeof(int) = 4, sizeof(float) = 4
** sizeof(struct user) = 20
sizeof(struct user) is supposed to return 18, but returned 20. What's wrong with the compiler - is it a bug?
-NO- it is not a bug. Sun Studio compiler(s) generate 32-bit code, and in that mode there is a significant run-time performance penalty for unaligned accesses, like accessing a 32-bit int which isn't aligned on a 32-bit dword boundary. To produce faster code, Sun Studio compiler(s) pads struct members so that each one can be accessed without delays; this sometimes produces struct size which is larger than the sum of the sizes of its members
If this is not the desired behavior and if we don't want to get the structure padded, we can let compiler know the same by using a compiler directive (aka
pragma) called "pack". Syntax of pragma pack:
#pragma pack(n)
n must be 0 or a power of 2. A value of other than 0 instructs the compiler to use the smaller of n-byte alignment and the platform's natural alignment for the data type. A value of 1 instructs the compiler not to perform any alignment. When n is 0 or omitted, the member alignment reverts to the natural alignment values.
If the value of n is the same as or greater than the strictest alignment on the platform, the directive has the effect of natural alignment
A pack directive applies to all structure definitions which follow it, until the next pack directive.
Lets include the pragma 'pack' in our source and run the program
bpte4500s001:/sunbuild1/giri/testcases/%cat aligndata.c
#include <stdio.h>
#pragma pack(1)
typedef struct user {
char name[10];
int age;
float salary;
} usr;
int main()
{
printf("\n ** sizeof(char) = %d, sizeof(int) = %d, sizeof(float) = %d\n ** sizeof(struct user) = %d\n", sizeof(char), sizeof(int), sizeof(float), sizeof(struct user));
return (0);
}
bpte4500s001:/sunbuild1/giri/testcases/%./a.out
** sizeof(char) = 1, sizeof(int) = 4, sizeof(float) = 4
** sizeof(struct user) = 18
Note:
When using #pragma pack on a SPARC platform to pack denser than the type's default alignment, the -misalign option must be specified for both the compilation and the linking of the application
Reference:
Sun Studio 9 C++ user's guide
Acknowledgements:
Dheeraj (aka tw|lit), Naresh Shroff