Segmentation Fault - how to solve it? CS50 PSET 4 - Recover

Viewed 42

I am trying to run this code for the pset4 where we have to recover jpegs from a file. I keep getting segmentation fault and did the debugging and found the problem is here:

else 
            {
                    fwrite(&buffer, 512, 1, jpg);

            }




Why would the program run into a segmentation fault here? Is it because I have not assigned enough memory for the jpeg file? Down is my code for reference.

Thanks!!



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

int main(int argc, char *argv[])
{

// Detects if a file is a JPEG

typedef uint8_t BYTE;

    // Check usage
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image \n");
        return 1;
    }

    // Open memory card
    FILE *file = fopen(argv[1], "r");

    if (!file)
    {
        printf("Could not open %s.\n", argv[1]);
        return 2;
    }

    // Repeat until end of card

    int jpegcounter=0;
    BYTE buffer[1000];
    char *name = malloc(jpegcounter);
    // Read 512 bytes into a buffer
    FILE *jpg=NULL;

    size_t bytes_read = fread(buffer, 512, 1, file);


do{

    fread(&buffer,512, 1, file);

    {
        // Check first four bytes for the header of a new JPEG to see if it's a new JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)

            {
                if(jpegcounter == 0)

                {
                    
                    sprintf(name, "%03i.jpg", jpegcounter);
                    jpg = fopen(name, "w");
                    if (jpg == NULL)
                         {
                        fprintf(stderr, "%s.\n", name);
                        return 3;
                         }
                    fwrite(&buffer, 512, 1, jpg);


                }

                else

                {
                    fclose(jpg);
                    sprintf(name, "%03i.jpg", jpegcounter);
                    jpg = fopen(name, "w");
                    if (jpg == NULL)
                         {
                        fprintf(stderr, "%s.\n", name);
                        return 3;
                         }
                    fwrite(&buffer, 512, 1, jpg);
                }
                jpegcounter++;
                printf("%i\n",jpegcounter);

            }

        else 
            {
                    fwrite(&buffer, 512, 1, jpg);

            }

        fclose(jpg);

    }
}
while (bytes_read == 512) ;

        fclose(jpg);
        free(buffer);
        fclose(file);
        return 0;
        

}
1 Answers

There is not enough memory assigned for name here char *name = malloc(jpegcounter);. jpegcounter is 0, so 0 bytes are allocated. It needs enough bytes to accommodate the full file name plus the null terminator (since it is a string created by sprintf).

Related