0

there is a problem in my recover program. when ever i run it, it always shows this command "free(): double free detected in tcache 2 Aborted (core dumped)."i cant point my finger to the error. Pls help me.it also shows an error to load my images.

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

typedef uint8_t BYTE;

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

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

     if(argc != 2)
     {
        printf("./Usage problem");
     }
    FILE *inputfile = fopen(argv[1], "r");

     if(inputfile == NULL)
     {
          printf("could not open file");
     }

     BYTE buffer[512];

     int filepointer = 0;
     FILE *picture = NULL;
     int jpeg = 0;

     char *filename = malloc(8 * sizeof(char));
     while (fread(buffer, sizeof(char), 512 ,inputfile))
    {
           if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
           {

               sprintf(filename , "%03i.jpg" , filepointer++);
               picture = fopen(filename , "w");
               fwrite(buffer,sizeof(buffer),1,picture);
               free(filename);
               jpeg++;


    }


    else if(picture != NULL)
    {
        fwrite(buffer,sizeof(char),1,picture);
    }


}

    free(filename);
    fclose(inputfile);
    fclose(picture);

    return 0;
}
1
  • please run your code through style50 before submitting in the future and make sure it is properly indented. additionally highlight the exact line where the problem is detected. you dont need to point your finger, put a comment on the line of code where it fails and include the error text.
    – UpAndAdam
    Commented Jan 2 at 17:49

1 Answer 1

1

Not hard to figure out. You have free(filename); inside your while loop. On the second pass, it will try to free filename after it's already been freed. Instant error.

You don't have to free filename after each use. The memory is allocated once in the malloc statement. You can reuse it over and over. You only need to free the memory at the end of the program (as you have done with the second free(filename); statement.)

Just remove the first free(filename); statement. ;-)

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

1
  • thank u very much for helping me.
    – dhan8293
    Commented Jan 2 at 13:58

You must log in to answer this question.

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