hello I am using ARM7 LPC2148. in the program I have to use recursive function. so there are lots of chances of stack overflow. how to avoid this??
The price you can pay for recursion is heavy stack use.
If you REALLY need to use recursion, then you should consider increasing the size of the stack accordingly.
Do you really have to?
Most recursive algorithms can be restructured into an iterative approach...
is there any way like using inline assembly in C operating on stack pointer??
I am using ARM7 LPC2148
What do you hope to achieve by that?
I just want to avoid stack overflow while working with recursive functions........
in LPC2148 there is inst in assembly with which we can set stack ptr mov sp, #data
No. You can use embedded assembly for that purpose, with serious risks of data corruption unless you know what you are doing:
__asm void not_a_good_idea_rtos_like_operations(void) { // instructions involving SP }
But what do you hope to achieve by this, actually? Better to drop recursion all together, probably.
So you intend to fool the compiler by manipulating the stack pointer yourself? What do you think do you have a compiler for, then? To write correct machine code that complies with the computation model/standards you use - of course! In other words: Don't do it.
"I just want to avoid stack overflow while working with recursive functions........"
You could use assembler to manipulate the stack. But to what purpose?
If your recursive function needs storage, then it simply needs storage. What would you attempt to do? put a temporary stack somewhere else? The total of space required would surely still be the same, so why go to the trouble?
Surely you have two options: 1) Increase the allocation for the stack. 2) Consider re-writing your routines so they don't require recursion.
I believe _any_ recursive algorithm can be transformed into an iterative version.
I thought so, but wasn't quite sure.
Do you have a reference for that?
The only real purpose I can think of is to detect when you're about to run out of stack, and stop the recursion there?
Not sure how actually useful that'd be, though...?
Again, the safest way to avoid problems due to recursion is: don't do recursion!
If you don't do it, then it obviously can't cause you any problems!
See:
en.wikipedia.org/.../Recursion_(computer_science)#Recursion_versus_iteration
(you'll need to copy & paste that - the forum can't cope with making it clickable)
"Another possible reason for choosing an iterative rather than a recursive algorithm is that in today's programming languages, the stack space available to a thread is often much less than the space available in the heap, and recursive algorithms tend to require more stack space than iterative algorithms."
So, again, if you're worried about stack space, don't use recursion!