0

I really need help, I'm getting a segfault error. Please look through my code and help me, please.

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


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

int count = 0;

int count1 = 0;

typedef uint8_t BYTE;

if (argc != 2)
{
    printf("Usage: ./recover image\n");
    return 1;
}

FILE *jpeg = fopen(argv[1], "r");

if (jpeg == NULL)
{
    printf("Usage: ./recover image\n");
    return 2;
}

BYTE arr[512];

char A[8];

FILE *img = NULL;

while (fread(arr, 512, 1, jpeg) == 1)

{

if (arr[0] == 0xff && arr[1] == 0xd8 && arr[2] == 0xff && (arr[3] & 0xf0) == 0xe0 && count == 0)

{

    sprintf(A, "%03i.jpg", count);

    count++;

    img = fopen(A, "w");

    fwrite(arr, 512, 1, img);
}



else if (arr[0] == 0xff && arr[1] == 0xd8 && arr[2] == 0xff && (arr[3] & 0xf0) == 0xe0 && count > count1)
{
   fclose(img);

   sprintf(A, "%03i.jpg", count);

   count++;

   img = fopen(A, "w");

   fwrite(arr, 512, 1, img);

}

else
{
   fwrite(arr, 512, 1, img);
 }


 }


fclose(img);

fclose(jpeg);


return 0;


}
4
  • fwrite(arr, 512, 1, img); caused the segfault, img is NULL. You can use this link to diagnose any segfaults of your code. Click "Start" to start. – stensal Jun 19 '20 at 20:52
  • @stensal thanks. Any idea of what I can do? Why is it going to NULL when it is supposed to continue writing? – Dave Jun 19 '20 at 21:06
  • It means img=fopen does not execute before fwrite, so It's a logic problem. Here is one debugging tip. Add printfs to your code to print out more info, and run your code to see how your code actually executes. – stensal Jun 19 '20 at 23:15
  • @stensalthanks. Also, awesome tool. – Dave Jun 20 '20 at 5:20

You must log in to answer this question.

Browse other questions tagged .