简体   繁体   English

C 错误:程序没有 memory 错误,valgrind 测试失败

[英]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:我正在做CS50 PSet 4 Recover 问题并得到以下错误:

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: Valgrind 说这条线有一个错误:

output_file = fopen(filename, "w");

But where in your code would you close 50 files?但是在你的代码中你会在哪里关闭 50 个文件? 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.否则,指向旧 FILE 结构的指针将丢失,并且您永远无法关闭文件,从而导致 49 memory 泄漏。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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