System.StackOverflowException

Dark Kai

Freshman
Joined
Sep 3, 2003
Messages
48
I've written a program to fill up a polygon(like in MSPaint). It worked fine in a small area but if i enlarge the area to fill then this error pops out during run time.
An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll
Why can't my recursive function run ??

here is part of my program

Code:
public function fill (byval x as integer,byval y as integer,byval colour as integer, byref imagearray(,) as integer)


      if imagearray(x,y)=colour then

            exit function

      else

            imagearray(x,y)=colour
            fill(x-1,y,colour,imagearray)
            fill(x+1,y,colour,imagearray)
            fill(x,y-1,colour,imagearray)
            fill(x,y+1,colour,imagearray)

      end if

end function
 
You are recursing too many times and therefore running out of space on the stack. A recursive function is not suitable to solve a problem like this because of the potential number of pixels involved. You could rewrite using a queue, or use the FloodFill API though.
 
uhh...Can I expend or increase the stack size ?? I don't understand what you meant by using a queue...Floodfill API might work but my imagebuffer is a User Defined Type (a structure of pixels). Thanks in advance.
 
No, you can't increase the stack size. At least, not for something like this - recursion just isn't appropriate.

You could investigate other means of maintaining context, using an array or collection-based class. Is there some reason you're using your own type for image data?
 
hmmmm....I'm using my own data type couze there are other info that i would like to bound with the image(I'm actually building a class). the reason i need this fill algorithm to work is couze i would like to select a region of interest in my image(ROI). meaning i will get this binary region(a frame with a filled polygon) and then further i will be able to process my image according to this binary region.

Attach with this is a illustration of the problem.
 
Back
Top