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
In C, at a much simpler level, consider the following;
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 (eg, 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).
Make sure you're using fixed point / integer math wherever possible. Lots of developers use floating-point math (along with the sluggish performance and large libraries & memory usage) when simple scaled integer math will suffice.
链接地址: http://www.djcxy.com/p/39642.html上一篇: 在C / C ++应用程序中分析过多代码大小的一些技术或工具是什么?
下一篇: 什么是减少C语言内存使用的最佳做法?