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.
main(int argc, char **argv)
union1.text="Welcome to StackOverflow";
the comments have more expertise regarding
unions in general.
Regarding your question specifically, this is my understanding:
Imagine instead of union you declare a
short int variable.
But then need to use a
long int. So you use
free on the
Then you use
malloc to allocate memory for a
long int. This has to be continguous memory. So now your memory looks like this.
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.