1

I am writing a C program that uses lots of recursive functions. I am also using a dynamic list to store some data while recursing. I implemented a Push function to push data into the list.

After several calls for the push function " > 17,000 times" i am getting the following error:

Unhandled exception at 0x77963c47 in Prob - Cap CE.exe: 0xC00000FD: Stack overflow.
at return HeapAlloc(_crtheap, 0, size ? size : 1); that is called from stack->listNode = malloc(sizeof(struct Node)); in the Push function.

I opened task manager and identified that I still have lots of free memory. So I guess it is not a memory leak issue.

Is there any limitation on how much I can add to the list, or how many times I can call a function?

Bo Persson
  • 90,663
  • 31
  • 146
  • 203

3 Answers3

9

The size of the stack allocated for a process is fixed. So even if the system has plenty of memory, you can overflow the stack.

What's more, your process itself usually has plenty of memory. It's just the stack that's quite small.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
5

">17,000 times" is not "several". It's bloody loads.

You can't expect your stack to hold 17,000 frames (and how much it can hold is implementation-dependent, and also depends on how much data is in each frame).

Use iteration instead.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    I made some more debugging and i found out that bloody loads of recursing is the real issue. It will be hard to use iteration instead of recursion because the code is pretty complicated :(. – Angela Beauty Aug 21 '11 at 21:10
2

Well, there will be limitations, for instance recursion can only go as far as the stack memory allocated for your app. Since you're getting a stack overflow, this seems like it is probably the problem.

See Change stack size for a C++ application in Linux during compilation with GNU compiler for some details on how to modify the stack size. If you can't get it to work right even with a huge stack, then it's likely you'll have to do some optimizations to reduce the amount of memory you're using, or to limit your recursions.

You could try moving some of your stack variables into the heap by allocating them rather than just doing local declarations, just as a first idea. If you could post some code as to what your recursive functions look like, we might be able to give suggestions. A likely solution to your ills is just to convert your functions from using recursion to using loops.

Community
  • 1
  • 1
shelleybutterfly
  • 3,216
  • 15
  • 32