プログラムを実行すると、解放され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
の後に次のエラー キャッチャーを追加しました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;
}