Node:union, Next:, Previous:Memory allocation, Up:Data structures


A union is like a structure in which all of the members are stored at the same address. Only one member can be in a union at one time. The union data type was invented to prevent the computer from breaking its memory up into many inefficiently sized chunks, a condition that is called memory fragmentation.

The union data type prevents fragmentation by creating a standard size for certain data. When the computer allocates memory for a program, it usually does so in one large block of bytes. Every variable allocated when the program runs occupies a segment of that block. When a variable is freed, it leaves a "hole" in the block allocated for the program. If this hole is of an unusual size, the computer may have difficulty allocating another variable to "fill" the hole, thus leading to inefficient memory usage. Since unions have a standard data size, however, any "hole" left in memory by freeing a union can be filled by another instance of the same type of union. A union works because the space allocated for it is the space taken by its largest member; thus, the small-scale memory inefficiency of allocating space for the worst case leads to memory efficiency on a larger scale.