0

Problem Statement: All the jpgs are rendered correctly however I get the following error when I run the cs50check. Expecting an error code of 0 but received the following on standard error instead — /opt/sandbox50/bin/run.sh: line 31: 30927 Segmentation fault stdbuf --error=0 --output=0 "$@"

My code is below.

int main(int argc, char* argv[]) { char buffer[512]; int jpgcount = 0; //count of number of jpegs char j1[4] = {0xff, 0xd8, 0xff, 0xe0}; char j2[4] = {0xff, 0xd8, 0xff, 0xe1};

FILE* outptr;

//open card file 
FILE* inptr = fopen("card.raw", "r");

if (inptr == NULL)
{
    printf("Could not open %s.\n", "card.raw");
    return 1;
}
//while loop to read through entire memory card while there is at least one item of size buffer remaning in file.
while (fread(buffer, sizeof(buffer), 1, inptr) ==1) 
    {     
        //check to see if signature of memory matches jpeg
        if ((buffer[0]==j1[0] && buffer[1] == j1[1] && buffer[2] == j1[2] && buffer[3] == j1[3]) || (buffer[0]==j1[0] && buffer[1] == j1[1] && buffer[2] == j1[2] && buffer[3] == j2[3]))
            {
                //close last file if it has contents in it
                if (outptr) 
                {   
                    fclose(outptr);
                }
                //create file name for outfile
                char filename[8];
                jpgcount++;
                sprintf(filename, "%03d.jpg", jpgcount);

                //open output file
                outptr = fopen(filename, "a");

                //write 512 bytes into the filename.
                fwrite(buffer, sizeof(buffer), 1, outptr);
            }
         else if (outptr!=NULL)
                //if outprt is still open writhe the block.
                {   
                    fwrite(buffer, sizeof(buffer), 1, outptr);
                }
            }

// close files
fclose(inptr);
fclose(outptr);
printf("All done, we have recovered your files.\n");
return 0;
1

the FILE* outptr is never initialized to NULL. So why are you assuming that the line

else if (outptr!=NULL)

or the one

if (outptr) 

will evaluate correctly? Also, just in case, remove that last printf. It's not expected by the grader. And i don't think it will cause any issues, but why do you open the jpeg file with "a" instead of "w"?

| improve this answer | |

You must log in to answer this question.

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