c++cgccgcc4gcc4.7

How to control or optimize or remove or deallocate unused memory in UNION's


This question about how to control or optimize or remove or deallocate unused memory in unions? We know that the union size is maximum data type descaled inside union. Suppose I declared long type then it allocates 64-bytes of memory but I used only 16-bytes in program. How to optimize the remaining 48-bytes of memory?

#include<stdio.h>
int main(){
  union data_type {
    unsigned long A;
    unsigned int B;
    unsigned short C;
    unsigned char D;
  };
  union data_type my_union;
  my_union.C = 0X09;
  printf("UNION size:%d\n", sizeof(my_union));
  return 0;
}

Solution

  • You cannot optimize or remove that memory. It's going to remain a waste of space and there's nothing you can do about it, if you use union like this. And this is one of the reasons why using union to create "variant" data types is considered bad practice: you end up wasting memory.

    If you wish to do generic programming in C, there are several better ways: void pointers combined with enum type information, or code adapted to C11 _Generic etc.