【发布时间】:2020-11-04 22:34:51
【问题描述】:
我也使用过 Valgrind,但仍然找不到错误。恢复图像是 CS50 问题。
#include <stdio.h>
#include<stdint.h>
#include <stdlib.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
if ( argc != 2)
{
printf("Usage : ./recover image\n");
return 1;
}
//Condition to check whether the file opens or not.
FILE *file = fopen(argv[1], "r");
int c=0;
FILE *img;
char *fileName = malloc(sizeof(char)*10);
if(fileName == NULL)
return 1;
//Below is the dynamic reading of file.
do
{
int *arr = malloc(sizeof(BYTE)*512);
if(arr == NULL)
return 1;
fread(arr,sizeof(BYTE),512,file);
if(arr [0] == 0xff && arr[1] == 0xd8 && arr[2] == 0xff && (arr[3] & 0xf0) == 0xe0)
{
if(c == 0)
{
img = fopen(" 000.jpg","a");// check for w or a
fwrite(arr,sizeof(BYTE),512,img);
}
else
{
fclose(img);
sprintf(fileName,"%03i.jpg",c);
img = fopen(fileName,"a");//check for w or a
fwrite(arr,sizeof(BYTE),512,img);
}
c++;
}
else
{
if(c!=0)
{
img = fopen(fileName,"a");
fwrite(arr,sizeof(BYTE),512,img);
}
}
free(arr);
}while(getc(file) != EOF);
if(img != NULL)
fclose(file);
fclose(img);
free(fileName);
}
【问题讨论】:
-
" 一切都无关紧要" - 这不是你写好问题的方式
-
你试过用gdb之类的调试器吗?
-
使用 valgrind 查找内存泄漏,使用 gdb 之类的调试器并读取回溯以解决运行时错误
-
OT:紧随其后:
FILE *file = fopen(argv[1], "r");应该是检查错误,而不是稍后的某些语句。所以在这个语句之后应该是:if( ! file ) { perror( "fopen for input file failed" ); exit( EXIT_FAILURE ); }这输出到stderr,你的错误信息和系统认为发生错误的文本原因。 -
关于:
int *arr = malloc(sizeof(BYTE)*512); if(arr == NULL) return 1;这没有通知用户发生了问题,也没有通知用户有关问题的详细信息。建议:int *arr = malloc(sizeof(BYTE)*512); if(arr == NULL) { perror( "malloc failed" ); fclose( file ); exit( EXIT_FAILURE ); }注意:表达式:sizeof( char )在 C 标准中定义为 1。将任何内容乘以 1 无效,只会使代码混乱。建议删除表达式:sizeof(BYTE)
标签: c computer-science cs50