简体   繁体   中英

C error: program is free of memory errors, valgrind tests failed

I am doing the CS50 PSet 4 Recover problem and get the below error:

program is free of memory errors
    valgrind tests failed; see log for more information. 

I don't understand what is the error, and therefore not sure how to fix it. I've tried using the debugger but it doesn't help.

My code is the below:

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


typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Check number of arguments
    if (argc != 2)
    {
        printf("Only one argument should be used\n");
        return 1;
    }

    // Open reading file
    FILE *input_file = fopen(argv[1], "r");
    if (input_file == NULL)
    {
        printf("Could not open file.\n");
        return 2;
    }

    // Store blocks of 512 bytes in an array
    BYTE buffer[512];

    // Keep track of number of images generated
    int count_image = 0;

    // File pointer for recovered images
    FILE *output_file = NULL;

    // Char filename
    char *filename = malloc (8 * sizeof(char));

    // Read the blocks of 512 bytes
    while (fread(buffer, sizeof(char), 512, input_file))
    {
        // Check if the bytes indicate start of JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            // Write the JPEG filenames
            sprintf(filename, "%03i.jpg", count_image);

            // Open output file for writing
            output_file = fopen(filename, "w");

            // Count number of images found
            count_image++;
        }

        if (output_file != NULL)
        {
            fwrite(buffer, sizeof(char), 512, output_file);
        }
    }

    free(filename);
    fclose(output_file);
    fclose(input_file);

    return 0;
}

Can someone please explain what I'm doing wrong? Valgrind says there's an error with the line:

output_file = fopen(filename, "w");

But where in your code would you close 50 files? You open them in a loop but only close once after the loop. You must close the old file whenever you open a new one. Otherwise the pointer to the old FILE structure is lost and you can never close the file resulting in 49 memory leaks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM