After running the program in valgrind -v it shows me that there are 3 unfreed blocks of memory (50 allocs, 47 frees). I’m probably failing to free infile outfile and temp – I guess. But when I put:
else {
free(line);
fclose(infile); /* added lines */
fclose(outfile); /* added lines */
free(temp); /* added lines */
exit(EXIT_FAILURE);
}
it doesn’t compile, showing me errors about undefined use of temp and outfile.
EDIT:
I changed it to (in lineRead):
else {
free(line);
fclose(infile);
return NULL;
}
and added following error catcher after while in main:
if ((check = readline(infile)) == NULL) {
fclose(outfile);
}
However, this gives me even more errors. Why is that?
/EDIT
How to fix that? I though that exit() does all the cleaning needed…
The code is changed in [1] because I wanted to simulate that particular error.
#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;
}
You didn’t free