在其中运行程序后,valgrind -v
它显示有 3 个未释放的内存块(50 个分配,47 个释放)。我可能无法释放infile
outfile
-temp
我猜。但是当我说:
else {
free(line);
fclose(infile); /* added lines */
fclose(outfile); /* added lines */
free(temp); /* added lines */
exit(EXIT_FAILURE);
}
它无法编译,向我显示有关未定义使用temp
and的错误outfile
。
编辑:
我将其更改为(在lineRead
):
else {
free(line);
fclose(infile);
return NULL;
}
while
并在in之后添加了以下错误捕获器main
:
if ((check = readline(infile)) == NULL) {
fclose(outfile);
}
然而,这给了我更多的错误。这是为什么?
/编辑
如何解决?我虽然这样exit()
做了所有需要的清洁......
代码在 [1] 中进行了更改,因为我想模拟那个特定的错误。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
char* lineRead(FILE* infile)
{
char* line = NULL;
char* newbuf = NULL;
int c;
size_t bufsize = 0;
size_t size = 0;
while((c=fgetc(infile)) != EOF) {
if (size >= bufsize) {
if (bufsize == 0)
bufsize = 2;
else if (bufsize <= ((size_t)-1)/2)
bufsize = size+1;
else {
free(line);
exit(EXIT_FAILURE);
}
newbuf = realloc(line,bufsize);
if (!newbuf) {
free(line);
exit(EXIT_FAILURE);
} else {
line = newbuf;
}
}
if (c != '\n') {
line[size++]=c;
}
}
if(size >= bufsize) {
if (size > (size_t)-1) /* [1] I know that there should be*/
/* '<', but it is '>' just for testing errors */
bufsize = size + 1;
else {
free(line);
exit(EXIT_FAILURE);
}
newbuf = realloc(line,bufsize);
if (!newbuf) {
free(line);
exit(EXIT_FAILURE);
}
line = newbuf;
}
line[size++]='\0';
return line;
}
int main(int argc, char* argv[])
{
char *line=NULL;
char **lines=NULL;
int linenumber=0;
int c;
void *temp=NULL;
while((line=lineRead(infile))!=NULL) {
linenumber++;
temp=realloc(lines, (linenumber)*sizeof(char*));
if(temp==NULL) {
printf("Bad alloc error\n");
free(lines);
return 0;
} else {
lines=temp;
}
}
/* processing lines */
free(lines);
return 0;
}