0

I keep getting segmentation fault on my code. I can't quite pinpoint where the problem lies, but it's most likely within my while loop. Would appreciate if someone can give me a hint or point where the error is. Thanks

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <cs50.h>

int main(int argc, char *argv[])
{
    // checks command line argument
    if (argc != 2)
    {
        // prompts user to use proper command line argument
        printf("usage: /recover image\n");
        return 1;
    }

    typedef uint8_t BYTE;
    BYTE buffer[512];
    int jpeg_count = 0;
    char file_name[8];
    FILE * jpg = NULL;

    //opens the file and reads
    FILE * card_file = fopen(argv[1], "r");
    //checks if file is empty
    if (card_file == NULL)
    {
        printf("file is NULL\n");
        return 1;
    }

    // reads until the end of the file
    while (fread(buffer, sizeof(BYTE), 1, card_file) == 1)
    {
        // checks if file starts with jpeg
        if (buffer[0] == 0xff && buffer[1] == 0xd8
            && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // checks if this is the first jpeg
            if (jpeg_count == 0)
            {
                //names the new file and proceeds on writing to create new jpeg 
                sprintf(file_name, "%03i.jpg", jpeg_count);
                jpg = fopen(argv[1], "w");
                fwrite(buffer, sizeof(BYTE), 1, jpg);
                jpeg_count++;
            }
            else
            {
                //closes the file and opens the next one
                fclose(card_file);
                sprintf(file_name, "%03i.jpg", jpeg_count);
                jpg = fopen(argv[1], "w");
                fwrite(buffer, sizeof(BYTE), 1, jpg);
                jpeg_count++;
            }
        }
        // if file doesn't start with jpeg
        else
        {
            //keep writing to the file
            fwrite(buffer, sizeof(BYTE), 1, jpg);
        }
    }
    fclose(card_file);
    fclose(jpg);
    return 0;
}
0

The problem lies here:

    else
    {
        //keep writing to the file
        fwrite(buffer, sizeof(BYTE), 1, jpg);
    }

Question: What happens when the first 512 byte data block from the input file is processed, but doesn't have a signature? What happens when this code tries to write to a null file pointer? Oh, wait. You already know. ;-)

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

| improve this answer | |

You must log in to answer this question.

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