0

my code can compile but when running it will return Segmentation fault. And when I apply "echo $?" to the code, it would return 139.

Here is my code.

/**
* Copies a BMP piece by piece, just because.
*/

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

int main(int argc, char *argv[])
{
  // ensure proper usage
if (argc != 2)
{
    fprintf(stderr, "Usage: ./recover infile\n");
    return 1;
}
    // remember filenames
char *infile = argv[1];
  // open input file 
FILE *inptr = fopen(infile, "r");

if (inptr == NULL)
{
    fprintf(stderr, "Could not open %s.\n", infile);
    return 2;
}

int buffer[512];
int number = 0;
FILE *img;
while(fread(buffer, 512, 1, inptr)>0)
{
    int status = 0;
    fread(buffer, 512 , 1, inptr);
    char filename[8];
    if (buffer[0]==0xff &&
        buffer[1]==0xd8 &&
        buffer[2]==0xff &&
        (buffer[3] & 0xf0)== 0xe0)
        {
            if(status==0)
            {
                sprintf(filename,"%03i.jpg",number);
                img = fopen(filename,"w");
                status = 1;
                fwrite(buffer, 512, 1, img);
                number ++;
            }
            else if(status==1)
            {
                fclose(img);
                sprintf(filename,"%03i.jpg",number);
                img = fopen(filename,"w");
                fwrite(buffer, 512, 1, img);
                number ++;
            }
        }
    else if(buffer[0]!=0xff)
    {
        if(status==1)
        {
            fwrite(buffer, 512, 1, img);
        }
    }
}
if(img)
{
  fclose(img);
}

    fclose(inptr);
    return 0;
}
0
0

Your status variable gets reset to zero each time you get a new block of data in the while loop. As a result of that, status does not stay 1 as you might have expected and status == 1 condition is never satisfied. This is probably causing the segmentation fault, as you are then not correctly writing to the files. You can try declaring status above the while loop.

0

The part

if(img)
{
  fclose(img);
}

might throw a segmentation fault and would work properly only if you initialized img like

FILE *img = NULL;

(you then could use img or img != NULL instead of status == 1)

You could also test for number instead, as that variable stays 0 until you open the first file. There's no need for a status variable at all.

And you already read in your loop head. Have only one fread!

Also, I totally don't get if(buffer[0]!=0xff)

Your buffer is of the wrong type, int probably is 8 bytes, not one. Use unsigned char, or uint8_t, or BYTE instead of int

You must log in to answer this question.

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