Home > Blockchain >  pset4 blur Segmentation fault
pset4 blur Segmentation fault

Time:09-26

I'm stuck on my code for too much time now and needing some help. I'm working on CS50 pset4 blur filter and I keep getting either a "Segmentation fault" or "Floating point exception" depending if try to change my " neighbour variables" on float instead of int. Can someone have any idea what I'm doing wrong with that ?

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // Copy image to "copy"
    RGBTRIPLE copy[height][width];
    for(int i = 0; i < height; i  )
    {
        for(int j = 0; j < width; j  )
        {
            copy[i][j] = image[i][j];
        }
    }
    // Loop through all the neighbour's pixel and calculate the average RGB in each
    int RedNeighbour = 0; int BlueNeighbour = 0; int GreenNeighbour = 0; int neighbourSum = 0;

    for(int i = 0; i < height; i  )
    {
        for(int j = 0; j < width; j  )
        {
            for(int k = i - 1; k < i   1; k  )
            {
                for(int l = j - 1 ; l < j   1; l  )
                {
                    if(k >= 0 && k < height && l >= 0 && l < width)
                    {
                        RedNeighbour  = copy[l][k].rgbtRed;
                        BlueNeighbour  = copy[l][k].rgbtBlue;
                        GreenNeighbour  = copy[l][k].rgbtGreen;
                        neighbourSum  ;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            // Divide each color by the sum of the neighbouring pixels and copy the pixe into original image
            image[i][j].rgbtRed = round(fmin(255, RedNeighbour/neighbourSum));
            image[i][j].rgbtBlue = round(fmin(255, BlueNeighbour/neighbourSum));
            image[i][j].rgbtGreen = round(fmin(255, GreenNeighbour/neighbourSum));
        }
    }
    return;
}

Thanks !

CodePudding user response:

I'd recommend just using a debugger (gdb, or your IDE's if you're using one) for that kind of thing.

That said, I'm noticing that on the following lines, you are potentially accessing out of bound indices in your copy array:

RedNeighbour  = copy[l][k].rgbtRed;
BlueNeighbour  = copy[l][k].rgbtBlue;
GreenNeighbour  = copy[l][k].rgbtGreen;

In your code, l is constrained by your width, while k is constrained by your height. However, the definition of the copy array is RGBTRIPLE copy[height][width];, which means that you should probably be accessing your copy array with copy[k][l] rather than copy[l][k].

  • Related