vinothvetrivel
vinothvetrivel

Reputation: 1

Size of Unions in C

How the union in C language allocate memory? For example

union st
{
int i;
char ch;
};

Upvotes: 0

Views: 582

Answers (3)

Matteo Italia
Matteo Italia

Reputation: 126877

In a union all the members share the same memory space (or, to say it as it is specified in the standard, if you take the address of any of the members you'll get the same result - besides the type). Obviously the size of the union is the size of its biggest member.

Because of this, the standard allows only one of the union members to be "active" at the same time, i.e. if you write in i, then you can only read from i, until you write in some other member. Failure to do so results in undefined behavior, which often is getting garbage results from reinterpreting bits of the other types.

Upvotes: 1

Cajunluke
Cajunluke

Reputation: 3113

It should be as big as its largest member. It has to be at least that large, and there's no reason for it to be larger.

Upvotes: 0

nmichaels
nmichaels

Reputation: 51009

An instance of that union will take up at least as much space as its biggest member, i.e. 1 word for the int.

If you had a union with a char and a short int, you might end up with a word on the stack anyway, since it's more efficient in most systems to allocate on word boundaries.

Upvotes: 4

Related Questions