I'm trying to submit code that is auto graded for uni, and I fail the last test case checking for memory being cleared and other errors. I have been looking at my code for hours and have no idea why it outputs errors
in use at exit: 0 bytes in 0 blocks
ERROR SUMMARY: 11 errors from 3 contexts (suppressed: 0 from 0)
This code is supposed to take either a file or stdin, and print out each line in reverse. It does that correctly without crashing. It even passes all the functional test cases.
#define _DEFAULT_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
int main(int argc, char ** argv){
FILE* file;
if(argc>1){
file = fopen(argv[1],"r");
}
else{
file=stdin;
}
//FILE* file = fopen(argv[1],"r");
//if(!(file))file=stdin;
int len=0;
char **array = malloc(sizeof(char*));
array[len] = malloc(sizeof(char)*255);
while(!(feof(file))){
fgets(array[len],255,file);
len ;
array = realloc(array,sizeof(char*)*(len 1));
array[len] = malloc(sizeof(char)*255);
}
for(int i=len;i>=0;i--){
printf("%s",array[i]);
}
for(int i=0; i<=len; i ){
free(array[i]);
}
fclose(file);
free(array);
return 0;
}
Any help would be appreciated thanks!
CodePudding user response:
You are not null terminating the last line
while (!(feof(file))) {
fgets(array[len], 255, file);
len ;
array = realloc(array, sizeof(char*) * (len 1));
array[len] = malloc(sizeof(char) * 255);
*array[len] = 0; <<<<==========
}
This at least produces good output now, dont knwo if valgrind complains or not because I am not on linux.