Thursday, 3 January 2013

What Is Wrong With This Piece Of Pseudo C Code ?


The idea for this blog sprang out of me doing a spring clean on my old laptop and finding all sorts of old training course and applications notes that I had written. This clean up got me thinking about some of the questions I had answered over the years and as I have been remembering them I have put them up.

Here is another question that came up regularly when I was supporting engineers programming DSPs in C. Frequently the Engineer would phone up and report that the hardware kept crashing. While this was entirely possible, my first place to start would often be to take a look at the project source code and the most common cause of the problem is shown here.

So what is wrong with this bit of code and why will it crash an application ?

.
.
int function (int param; .....)
{
int array [2000];
.
.

The answer is that the array is placed on the stack and while many compilers (Microsoft, Borland, GCC and the like) leave as much space between the stack and the heap as possible, this is not always possible on an embedded processor, with limited memory available, so the end result is that the stack starts to encroach on the heap and finally disaster strikes.

Most embedded linkers include a linker command file that allows the programmer to specify the position and size for the code, the stack, the heap and all the other memory blocks. While it is entirely possible to specify a larger stack space in the linker command file, this always seems to me like an unnecessary hack that is bound to end in tears because at some point in the future someone else is going to have to maintain the code and will not be looking for some hidden parameters in the LCF.

Far better, in my mind, is to allocate all arrays at the top level of the application, using malloc () and that way, if the application runs out of memory you will get an error message that can be easily detected and handled.

Having malloc'd the array at the top level then pointers can be passed to the sub-functions. This not only avoids the stack/heap problem discussed above but also makes the code re-entrant and a lot more portable.

A final word on compilers for Windows/Linux etc. While the latest Microsoft linker (And I assume GCC etc are the same) allocates 1 MByte for the stack so there is way more to play with. I still think allocating arrays onto the stack is bad form so I avoid doing it here as well.

If you have found this solution useful then please do hit the Google (+1) button so that others may be able to find it as well.

Numerix-DSP Libraries : http://www.numerix-dsp.com/eval/

Copyright © 2013 Delta Numerix

No comments:

Post a Comment