0

For pset4 'Recover', I'm facing a segmentation fault but I cannot find what I did wrong in my code. If I use echo$? to find where the bug is, it returns the value 1. Can someone help me to point me in the right direction to fix this segmentation fault error?

This is my code:

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

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

  // check for command-line argument + image file
  if (argc != 2)
  {
    fprintf(stderr, "./recover image\n");
    return 1;
  }

  // remember file name
  char *infile = argv[1];

  // open forensic image for reading
  FILE *inptr = fopen(infile, "r");
  if (inptr == NULL)
  {
    fprintf(stderr, "Could not open %s.\n", infile);
    return 2;
  }

  // declare some variables and values
  unsigned int block[512]; // array of one block of memory
  int counter = 0; // counter for jpeg
  FILE *img; // img file pointer

  // main program
  while (fread(block, sizeof(block), 1, inptr))
  {
    // identified jpg
    if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] = 0xf0) == 0xe0)
    {
        // close open files
        if (counter > 0)
        {
            fclose(img);
        }

        // create filename
        char filename[7];
        sprintf(filename, "%03i.jpg", counter);

        // open file
        img = fopen(filename, "w");

        // check if jpg file is successfully created
        if (img == NULL)
        {
            fclose(inptr);
            fprintf(stderr, "Could not create output JPG %s", filename);
            return 3;
        }

        // increment counter
        counter++;
    }

    // write into file
    fwrite(block, sizeof(block), 1, img);

}

// close open files
fclose(inptr);
fclose(img);

return 0;}
0

It's good that you want to know how to find the problem. This is a very important skill to perfect in debugging code.

You can start by identifying which line of code is causing the seg fault. Run it in debug50 and step through each line of code until it fails.

Sometimes, the debugger masks the seg fault and you can't replicate it. When that happens, it's time for another approach. Insert unique printf statements in the code at strategic locations. After each run, add or move printf statements until you have placed printf statements on either side of the offending line of code. Then, you'll know which line.

Once you know which line, you can figure out why it's seg faulting, and you can fix it.

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

You must log in to answer this question.

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