0

I have been working on the recover.c part of pset4. While it took me a while, I feel I have the code figured out. While my method is different from that of some other people, I feel it is correct. However, while running the program it segfaults. After countless times using valgrind and gdb, the program seg faults while executing the following line(s). long q = ftell(card); printf("%ld", q); fseek(card, (-1 * 4), SEEK_CUR); * PS I made the long q to help find any errors with my fseek. While I know there are definitely some errors with the program, I have narrowed it down to an error with the file pointer C. Even when I run it in gdb, and try to print the value of ftell(card) ahead of time, gdb segfaults and stops.

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


 int main(int argc, char* argv[])
{   
BUFFER a;
uint8_t apple[512] = {};
if (apple == NULL)
{
    printf("OUT OF MEMORY.\n");
    return 1;
}
int b = 0;


FILE* card = fopen("card.raw", "r");
if (card == NULL)
{
    fclose(card);
    printf("Couldn't open file. \n");
    return 1;
}

while(b < 16)
{
    fread(&a, sizeof(BUFFER), 1, card);
    if (a.a == 0xff && a.b == 0xd8 && a.c == 0xff)
        {
            if(a.d == 0xe1 || a.d == 0xe0)
            {
                char title[7] = {};
                sprintf(title, "%.3d.jpg", b);
                FILE* img = fopen(title, "w");
                if (img == NULL)
                {
                    fclose(img);
                    printf("Couldn't open file.\n");
                    return 1;
                }
                long q = ftell(card);
                printf("%ld", q);
                fseek(card, (-1 * 4), SEEK_CUR);
                fread(apple, (sizeof(uint8_t) * 512), 1, card);
                fwrite(apple,(sizeof(uint8_t) * 512), 1, img);
                fclose(img);
                b++;
            }
            fseek(card, 508, SEEK_CUR);
        }       
    else 
    {
        fseek(card, 508, SEEK_CUR);
    }   
}
fclose(card);
return 0; 
}

Please help in finding the error or problem with my code. Thanks in advance.

CODE FOR RECOVER.H

#include <stdint.h>

typedef uint8_t  BYTE;
typedef uint32_t DWORD;
typedef int32_t  LONG;
typedef uint16_t WORD;

typedef struct
{
BYTE a;
BYTE b;
BYTE c;
BYTE d;
}
BUFFER;
0

You are not verifying whether your freads were successful or not. See Week 4-> Shorts-> File I/0. Jason discusses this around the 8:15 mark. He's using fgets in the video, but the same advice applies to fread.

You must log in to answer this question.

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