Search code examples
cembeddedheap-memorysystemstack-size

C embedded systems stack and heap size


How could I determine the current stack and heap size of a running C program on an embedded system? Also, how could I discover the maximum stack and heap sizes that my embedded system will allow? I thought about linearly calling malloc() with an increasing size until it fails to find the heap size, however I am more interested in the size of the stack.

I am using an mbed NXP LPC1768, and I am using an offline compiler developed on GitHub called gcc4mbed.

Any better ideas? All help is greatly appreciated!


Solution

  • For this look at your linker script, this will define how much space you have allocated to each.

    For stack size usage do this:

    At startup (before C main()) during initialization of memory, init all your stack bytes to known values such as 0xAA, or 0xCD. Run your program, at any point you can stop and see how many magic values you have left. If you don't see any magic values then you have overflowed your stack and weirdness may start to happen.

    At runtime you can also check the last 4 bytes or so (maybe last two words, this is really up to you). If they don't match your magic value then force a reset. This only works if your system is well behaved on reset and it is best if it starts up quick and isn't doing something "real time" or mission critical.

    Here's a really helpful whitepaper from IAR on the subject.