I'm doing a small drawing program and trying to implement a floodfill.

My problem is that the stack keeps overflowing, obviously because the recursion is to deep. I've tried this code in DOS and in Windows and both cause stack overflows. I've also looked for an iterative algorithm for this, but all the docs and sites use the recursive one. However, they fail to mention that since you are pushing return addresses on the stack every time you call a function, that the stack can overflow if it does not return.

Code:
//256 color example
//hi-color would use RGB color or RGBA color
void FloodFill(int x,int y,int color,int oldcolor)
{
  if (x<left || x>right || y<top || y>bottom) return;

  int test=GetPixel(x,y);
 
  if (test==oldcolor)
  {
     PlotPixel(x,y,color);
     FloodFill(x+1,y,color,oldcolor);
     FloodFill(x,y+1,color,oldcolor);
     FloodFill(x-1,y,color,oldcolor);
     FloodFill(x,y-1,color,oldcolor);
  }
  else return;
}
But this will cause the stack to overflow even with a stack size of 64000 bytes, which is very large.

There has to be a way to floodfill w/o overflowing the stack.

On hi-res screens, this will need a very large stack ((width*height)/4) and for hi-color it will need even more.
Is there a better way?


Please help.