I am working on a recursive flood-fill function with 4-connected neighbours as part of a drawing application program. However, my attempts keep resulting in the program crashing. I am coding in C, however I will just post pseudo-code of my algorithm. I am hoping somebody can help me see what I am missing or the flaw in my methodology.

Function arguments:
* screen struct(includes data and dimensions)
* x-coordinate
* y-coordinate

Function name: fill_new


if data(x,y) == pixel on || x > screen width || y > screen height || y less than 0 || x < 0
    return;

otherwise
{
    plot on pixel in data(x,y)

    loop i from -1 to 1 in steps of 1
    {
        xn = x + i;
        yn = y + i;

        if data(x,y) pixel off
        {
            call fill_new for coordinates (xn, y)
            call fill_new for coordinates (x, yn)
        }

    }
 }

The first line the order of the or'd conditions suggest that you check the data before validating the indexes you use to access the data. You need to validate the indexes first otherwise you could use out of range values.

Again in the loop you calulate xn and yn and use it without validating those values to check they are valid but if x == screen height then x+1 is out of range and if x = 0 x - 1 is out of range, similarly for y.