![](/img/trans.png)
[英]Program is free of memory errors, valgrind tests failed - CS50 pset5 speller
[英]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.