Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What are some best practice for "Memory Efficient C programming". Mostly for embedded/mobile device what should be the guidelines for having low memory consumptions ?

I guess there should be separate guideline for a) code memory b) data memory

like image 941
user27424 Avatar asked Jan 01 '09 06:01

user27424


2 Answers

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.
like image 106
SmacL Avatar answered Sep 19 '22 03:09

SmacL


A few suggestions that I've found useful in working with embedded systems:

  • Ensure any lookup tables or other constant data are actually declared using const. If const is used then the data can be stored in read-only (e.g, flash or EEPROM) memory, otherwise the data has to be copied to RAM at start-up, and this takes up both flash and RAM space. Set the linker options so that it generates a map file, and study this file to see exactly where your data is being allocated in the memory map.

  • Make sure you're using all the memory regions available to you. For example, microcontrollers often have onboard memory that you can make use of (which may also be faster to access than external RAM). You should be able to control the memory regions to which code and data are allocated using compiler and linker option settings.

  • To reduce code size, check your compiler's optimisation settings. Most compilers have switches to optimise for speed or code size. It can be worth experimenting with these options to see whether the size of the compiled code can be reduced. And obviously, eliminate duplicate code wherever possible.

  • Check how much stack memory your system needs and adjust the linker memory allocation accordingly (see the answers to this question). To reduce stack usage, avoid placing large data structures on the stack (for whatever value of "large" is relevant to you).

like image 23
ChrisN Avatar answered Sep 22 '22 03:09

ChrisN