Memory Allocation for Structure and Union - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts

Memory Allocation for Structure and Union

Share This

Let us try to understand the memory allocation for Structure and Union variables.

Can you calculate the memory allocation for the following structure? Before proceeding, let us check memory allocation for the primitive data types. 

#include<stdio.h> int main (void) { printf("%d\n", sizeof(int)); printf("%d\n", sizeof(char)); printf("%d\n", sizeof(float)); printf("%d\n", sizeof(short)); printf("%d\n", sizeof(double)); printf("%d\n", sizeof(long)); return 0; }
#include<stdio.h> struct test { char a; double b; int c; char d; float e; char f[3]; }; int main (void) { printf("%d", sizeof(struct test)); return 0; }
You may calculate the memory allocation for the above structure, which seems 21 Bytes. However, the actual result is 32 Bytes.
To understand the result, you have to start with a very small structure.

#include<stdio.h> struct test { char a; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x\n", &t.a); return 0; }
Here, the result is 1 Byte. If we define the structure as follows:

#include<stdio.h> struct test { char a; double b; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x\n", &t.a, &t.b); return 0; }
The result is 16 Bytes. If we add an integer variable as follows:

#include<stdio.h> struct test { char a; double b; int c; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x %x\n", &t.a, &t.b, &t.c); return 0; }
The memory allocation is 24 Bytes. But the surprising thing comes in the following example. If the positions are changed as follows:
#include<stdio.h> struct test { char a; int c; double b; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x %x\n", &t.a, &t.c, &t.b); return 0; }
The memory allocation is 16 Bytes, even though the members are the same.

#include<stdio.h> struct test { char a; int c; char d; double b; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x %x %x\n", &t.a, &t.c, &t.d, &t.b); return 0; }
The memory allocation is 24 Bytes. If the variable d is declared before variable c, memory allocation becomes 16 Bytes as follows:
#include<stdio.h> struct test { char a; char d; int c; double b; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x %x %x\n", &t.a, &t.d, &t.c, &t.b); return 0; }
The memory allocation is 16 Bytes.

#include<stdio.h> struct test { char a; short e; char d; int c; double b; }; int main (void) { printf("%d", sizeof(struct test)); printf("\n%x %x %x %x %x\n", &t.a, &t.e, &t.d, &t.c, &t.b); return 0; }
Here, the memory allocation is 24 Bytes. But if the variable e is declared after variable d, memory allocation becomes 16 Bytes.

Happy Exploring!

No comments:

Post a Comment