What are some best practices for reducing memory usage in C?

In C, at a much simpler level, consider the following;

  • Use #pragma pack(1) to byte align your structures
  • Use unions where a structure can contain different types of data
  • Use bit fields rather than ints to store flags and small integers
  • Avoid using fixed length character arrays to store strings, implement a string pool and use pointers.
  • Where storing references to an enumerated string list, e.g. font name, store an index into the list rather than the string
  • When using dynamic memory allocation, compute the number of elements required in advance to avoid reallocs.

Leave a Comment