0

guys i dont know why but i have sigmentation fault help please

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */
 #include<stdio.h>
 #include<cs50.h>
 #include<stdlib.h>
 #include<stdint.h>
 #include<string.h>

int main(void)
{
    FILE *fp = fopen("card.raw","r");
    if(fp == NULL)
    {
        fclose(fp);
        {
            printf("cant open file\n");
            return 1;
        }
    }
    FILE *outptr;
    int jpgcount = 0;
    uint8_t buffer[512];
    {
        fread(buffer,512,1,fp);
    }
    while(fread(buffer, 512, 1, fp) > 0)
    {
        if(buffer[0] == 0xff &&
        buffer[1] == 0xd8 &&
        buffer[2] == 0xff &&
        (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        {
            {
                fclose(outptr);
                jpgcount++;
            }
            char filename[8];
            {
                sprintf(filename,"%03i.jpg",jpgcount);
            }
            {
                    outptr = fopen(filename, "w");
                    fwrite(buffer, sizeof(buffer), 1, outptr);
            }
        }
    }
        fclose(outptr);
        fclose(fp);
        return 0;
}    
1
  • You could find the incorrect line yourself by debugging. Try to put a breakpoint in CS50 IDE and do this: > make yourprogram > debug50 ./yourprogram
    – paul
    Dec 9 '16 at 13:57
1

The seg fault is being caused by the following line inside the while loop:

fclose(outptr);

The reason is that the first file hasn't been opened yet. But since you've already moved on to other issues, I'll assume that you found the problem. ;-)

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

0

The line 20 ("fclose(fp);") is odd, try to remove it. You cannot close a file when it was not opened.

2
  • Right idea, wrong line. Yes, that line would generate a seg fault if it ever executed, but that will only happen if the input card.raw file doesn't open. The seg fault is actually being caused by trying to close an output file that has never been opened. See my answer. But points for catching that error! ;-)
    – Cliff B
    Dec 8 '16 at 22:33
  • Haha, nice! Indeed. Thank you Cliff!
    – paul
    Dec 9 '16 at 13:56

You must log in to answer this question.

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