-4

hi guys when i run this code it keeps prompting segmentation fault. can anyone tell me whats going on? appreciate all the help. when i try the debugger it also stops halfway thus i cant identify where is my mistake. no matter how i change my code the result is still the same T.T

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

typedef uint8_t BYTE;
 
int main(int argc, char *argv[])
{

    if (argc > 2)
    {
        return 1;
    }
    
    BYTE buffer[512]; 
    
    FILE *file = fopen(argv[1], "r");
    
    if (file == NULL)
    {
        return 1;
    }

    int count = 0;
    FILE *img;
    while (fread(buffer, sizeof(BYTE), 512, file) != 0)
    {
        fread(buffer, sizeof(BYTE), 512, file);
        char filename[100];
        //start of jpeg
        if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0))
        {
            // not first jpeg file
            if (count != 0)
            {
                fclose(img);
                count++;
                sprintf(filename, "%03i.jpg", count);
                img = fopen(filename, "w");
                fwrite(buffer, sizeof(BYTE), 512, img);
            }
            //first jpeg
            else
            {
                sprintf(filename, "%03i.jpg", count);
                img = fopen(filename, "w");
                fwrite(buffer, sizeof(BYTE), 512, img);
            }
        }
        //not start of jpeg
        else
        {
            fwrite(buffer, sizeof(BYTE), 512, img);
        }
    }
    
    fclose(file);
    fclose(img);
    return 0;
}

1 Answers1

0

You can use

help50 valgrind ./recover card.raw

to try and make sense of valgrind error logs when debugging memory issues.

You have an uninitialised pointer FILE *img;; you're skipping 512bytes each time

while (fread(buffer, sizeof(BYTE), 512, file) != 0)
    {
        fread(buffer, sizeof(BYTE), 512, file);

and your char filename[100] is reserved for 99 characters, but you only set 7 of them when sprintf(filename, "%03i.jpg", count), which may not result in an error but is less than optimal memory management.