簡體   English   中英

C 錯誤:程序沒有 memory 錯誤,valgrind 測試失敗

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

我正在做CS50 PSet 4 Recover 問題並得到以下錯誤:

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

我不明白錯誤是什么,因此不知道如何解決它。 我試過使用調試器,但沒有幫助。

我的代碼如下:

#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;
}

有人可以解釋我做錯了什么嗎? Valgrind 說這條線有一個錯誤:

output_file = fopen(filename, "w");

但是在你的代碼中你會在哪里關閉 50 個文件? 您在循環中打開它們,但在循環后僅關閉一次。 每次打開新文件時都必須關閉舊文件。 否則,指向舊 FILE 結構的指針將丟失,並且您永遠無法關閉文件,從而導致 49 memory 泄漏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM