Naresh Naresh - 11 months ago 54
C Question

How does union prevent memory fragmentation?

I am going through this link and learning C. Interesting part on the page:

The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union.

I understand this part by the following code:

typedef struct{
char name[100];
int age;
int rollno;

typedef union{
student *studentPtr;
char *text;

main(int argc, char **argv)
typeUnion union1;

//use union1.studentPtr

union1.text="Welcome to StackOverflow";
//use union1.text

return 0;

Well, in the above code
is reusing the space previously used by
, not completely but still using.

Now, the part I don't understand is, when is the freed up space of
can't be used which leads to memory fragmentation?

edit: Going through the comments and answers, it is imperative to use the classic text, adding this edit to the post presuming it will help beginners like me

Answer Source

the comments have more expertise regarding unions in general.

Regarding your question specifically, this is my understanding:

  • union sets aside memory for the largest datatype in the union variable. So for example having a short int and a long int in the union will set aside enough memory for a long int 2 bytes set aside for long int

  • Imagine instead of union you declare a short int variable.1 byte for small int But then need to use a long int. So you use free on the short intfreeing small int memory Then you use malloc to allocate memory for a long int. This has to be continguous memory. So now your memory looks like this. enter image description here With a free byte in the middle of an otherwise used block of memory. Sitting there waiting for you to request specifically 1 byte of memory.

Aside: If you're learning c I recommend the classic text. It's dated but I love the simplicity, clarity and text-book style approach.