1

i am trying to solve the recover issue. When I run my programm I get: * Error in `./recover': free(): invalid pointer: 0x0000000001da5200 * Aborted

I don't know how to proceed. Can someone please point me in the right direction? Thanks in advance!

    //stops the programm is usage incorrect
    if(argc != 2){
        fprintf(stderr, "Usage: ./recover file.jpg\n");
        return 1;
    }




    //opens the file to recover
    FILE *raw_file = fopen(argv[1], "r");
    if(raw_file == NULL){
        fprintf(stderr, "Cannot open file\n");
        return 2;
    }

    //creates the buffer for storage
    unsigned char * buffer = (unsigned char*)malloc(512);

    char filename[7];
    int counter = 0;
    for(int i = 0; i < sizeof(raw_file); i++)
    {

    sprintf(filename, "%03i.jpg", counter);

    //reads 512 bytes in the buffer
    fread(buffer, 512, 1, raw_file);



    //check for jpeg and write if
    if(buffer[0] == 0xff &&
        buffer[1] == 0xd8 &&
        buffer[2] == 0xff &&
        (buffer[3] & 0xf0) == 0xe0){
            //write the new file
            FILE *outfile = fopen(filename, "w");
            fwrite(buffer, 512, 1, outfile);
            fclose(outfile);
            counter++;
        }

    fseek(raw_file, 1, SEEK_SET);

    }
    free(buffer);

    fclose(raw_file);
    return 0;

}
0

I don't know where your error is happening, have you tried stepping through the programme using debug50? Here are a few thoughts:

  1. filename is too short. It needs to be three digits plus four characters ".jpg", plus the string terminator '\0', so using sprintf, you write 8 characters to a 7 character char array.

  2. The loop for(int i = 0; i < sizeof(raw_file); i++) won't work. sizeof(raw_file) tells you how many bytes a pointer on your system has. Maybe something like while (!feof(raw_file)) would work better.

  3. On a matching header, you don't want to close the outfile immediately. Declare that variable outside the loop, and if there is an open outfile, close it just before opening a new one. You then would need to close the last file (if there's any) after the loop. And even if the header does not match, if there's an open outfile, write to it, just don't start a new file then.

  4. I don't get your fseek. Just does not make sense to me. You don't need any.

You must log in to answer this question.

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