-1

In structure, memory space will be created for all members inside structure. In union memory space will be created only for a member which needs largest memory space. Consider the following code:

struct s_tag
{
   int a;
   long int b;
} x;

struct s_tag
{
   int a;
   long int b;
} x;

union u_tag
{
   int a;
   long int b;
} y;

union u_tag
{
   int a;
   long int b;
} y;

Here there are two members inside struct and union: int and long int. Memory space for int is: 4 byte and Memory space for long int is: 8

So for struct 4+8=12 bytes will be created while 8 bytes will be created for union. I run the following code to see a proof: C

#include<stdio.h>
struct s_tag
{
  int a;
  long int b;
} x;
union u_tag
{
     int a;
     long int b;
} y;
int main()
{
    printf("Memory allocation for structure = %d", sizeof(x));
    printf("\nMemory allocation for union = %d", sizeof(y));
    return 0;
}

But I can see the following output:

Memory allocation for structure = 16
Memory allocation for union = 8

Why memory allocation for struct is 16 instead of 12? Is there any wrong in my understanding?

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72

2 Answers2

1

Most likely the requirement for aligning memory access on X byte boundaries. Also, it's up to the compiler - it can do what it likes.

LoztInSpace
  • 5,584
  • 1
  • 15
  • 27
0

The compiler adds invisible padding bytes between the two struct members which make sure that the address of the long member is a multiple of sizeof(long), so that the variable is correctly aligned in memory. Depending on the CPU architecture, if a variable is not correctly aligned, accesses to it might crash the program, result in incorrect values, just be slow or work as expected.

Erlkoenig
  • 2,664
  • 1
  • 9
  • 18