0

在其中运行程序后,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);
} 

它无法编译,向我显示有关未定义使用tempand的错误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;
}
4

2 回答 2

2

你没有自由

newbuf // in read line
line // in main
temp // Which gets free'd only on after bad malloc
于 2012-09-01T14:05:21.643 回答
0

你没有说你添加 free()s 去了哪里,但如果它在 lineread 中,那么那些其他变量在那里不可见(它们被声明为 main 本地;你在这里定义了一个不同的行)。因此,您需要将它们作为参数传递或将它们设为全局。

于 2012-09-01T14:03:19.270 回答