0

I keep getting a segmentation fault in my recover.c and I am not sure why. I have been stuck on this one for days. The idea is that we are trying to recover some deleted jpg files from a card.

Thank you ahead of time!

#include <cs50.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
 
//typedef uint8_t BYTE;
 
int main(int argc, char *argv[])
{
    // Check for proper usage
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }
    
    // Open file
    FILE *file = fopen(argv[1], "r");
    if (file == NULL)
    {
        fprintf(stderr, "Could not open %s.\n", argv[1]);
        return 1;
    }
    
    // Read file
    int i = 0;
    char *filename[8];
    uint8_t buffer[512];
    FILE *img = NULL;
    
    while (fread(&buffer, 512, 1, file) == 1)
    {
        // Start of new jpeg
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // Close old jpeg if it exists
            if (i >= 1)
            {
                fclose(img);
            }
            
            // Create new file    
            i++;
            sprintf(*filename, "%03i.jpg", i);
            img = fopen(*filename, "w");
            if (img == NULL)
            {
                return 3;
            }
        }
        
        // Continue writing to file as long as an image was found
        if (i >= 1)
        {
            fwrite(&buffer, 512, 1, img);
        }
    }

    // Close the remaining files
    fclose(img);
    fclose(file);
    return 0;
}```
1

Simple problem. Look at the declaration:

    char *filename[8];

This creates an array of 8 pointers to chars, not an array (a string) of 8 chars. Remove the asterisks in the code.

Then, there's another problem. What's the name of the first file supposed to be? ;-)

Finally, you might find this thread useful:

Do YOU know how to find a seg fault?? Advice to new programmers

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

2
  • Thank you so much!!! That was such a simple fix (': – Summer Ng Jan 31 at 7:32
  • Simple, once you gain experience. For a new programmer, it's difficult to spot these things, That's just the way it is. ;-) – Cliff B Jan 31 at 7:56

You must log in to answer this question.

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