0

I'm currently trying out cs50's pset4 filter (less comfortable). The program compiles but when run, it outputs segmentation fault. When using check50, it showed that my reflect code passed three of their checks, but failed the other two, which I have pasted below. Could anyone give any suggestions? Thanks!

// Reflect image horizontally
void reflect(int height, int width, RGBTRIPLE image[height][width])
{
    double middle;
    int mid;
    middle = (width - 1)/2;
    for (int i = 0; i < height; i++)
    {
        if (middle == 0)
        {
            break;
        }
        else
        {
            mid = (int) round(middle);
            for(int j = 0; j < mid; j++)
            {
                RGBTRIPLE temp[i][j];
                int val = width - (j + 1);
                temp[i][j] = image[i][j];
                image[i][j] = image[i][val];
                image[i][val] = temp[i][j];
            }
        }
    }
    return;
}

:( reflect correctly filters 1x2 image
    expected "0 0 255\n255 0...", not "255 0 0\n0 0 2..."
:( reflect correctly filters 4x4 image
    expected "100 110 120\n7...", not "100 110 120\n4..."
0

Have you identified which line is causing the seg faults? You might find this thread helpful: Do YOU know how to find a seg fault?? Advice to new programmers

Now, look closely at this code:

for (int i = 0; i < height; i++)
{
    ...
        for(int j = 0; j < mid; j++)
        {
            RGBTRIPLE temp[i][j];

When temp is declared, what are the values of i and j??? Shouldn't these be height and width instead? That's where the seg fault is being generated. This declares an array that is too small for the numbers being used.

Better question: Why use an array here at all? The only purpose temp serves is to be a temporary holder while swapping two other pixels. After each swap, the value in the temp var no longer matters. Instead, you could just create a single pixel var that gets reused over and over, RGBTRIPLE temp; and completely eliminate the problem.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

2
  • Thanks! :-) I tried this and it solved the segmentation fault but not the errors shown by check50! I found another method which passed all the check50 checks, but I'm still at a loss why this code doesn't..
    – panda384
    Aug 11 at 11:11
  • Well, the question was how to solve the seg fault. We don't know if you've worked on the other issues. That's why it's "One problem, one question." :-)
    – Cliff B
    Aug 11 at 11:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .