0

My code has been suffering from a seg fault, I followed the logic from the walkthrough pseudocode but unfortunately I cant seem to fix the issue.

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

typedef uint8_t BYTE;


int main(int argc, char *argv[])
{
    FILE *file = NULL;
    FILE *file2 = NULL;

    if(argc != 2)
    {
        return 1;
    }
    else
    {
       //open the card raw file in read form
        file = fopen(argv[1], "r");
        if (!file)
        {
            return 1;
        }
    }

    int counter = 0;
    BYTE buffer[512];
    char filename[8];

    while((fread(buffer, 1, sizeof(buffer), file)) == 512) //checking if EOF
    {

        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
        {
            if (counter == 0) //if first jpeg start writing 
            {
                sprintf(filename, "%03i.jpg", counter);
                file2 = fopen(filename, "w");
                fwrite(buffer, 1, 512, file2); 
                counter++;  
            }
            else
            {
                fclose(file2); //if already found jpeg,close previous file
                sprintf(filename, "%03i.jpg", counter); 
                file2 = fopen(filename, "w"); //writing to new file
                fwrite(buffer, 1, 512, file2); 
                counter++;  

            }

        }
        else //this is the bit with the issue I reckon
        {
            fwrite(buffer, 1, 512, file2); //no new jpeg so continue writing 512 bytes
        }
    }



    fclose(file);

    fclose(file2);

}
  • Can you use valgrind and debug50 on it to provide more info on what causes the seg fault – Ojou Nii Jun 12 at 15:37
0

Don't assume that the first time you read from the file you're going to find the header. You need to find a way to get rid of those first readings until the first header shows up.

| improve this answer | |
  • I've fixed it now thanks, didn't spot that somehow. I also had to change the last else statement to: else if(file2 != NULL) – Anurag Reggie Jun 12 at 20:06
0

fwrite(buffer, 1, 512, file2); caused the segfault. The reported error message, and the link to reproduce/debug this error. Click "Start".

  Memory access error: invalid parameter; abort execution.
  # fwrite's 4th parameter is not a valid FILE pointer.
  # Stack trace (most recent call first) of the error.
  # [0]  file:/recover.c::56, 13
  # [1]  [libc-start-main]
| improve this answer | |
  • I've fixed it now thanks, had to change the last else statement to: else if(file2 != NULL) – Anurag Reggie Jun 12 at 20:04

You must log in to answer this question.

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