Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C, Why Is Valgrind Showing Errors Detected For This Code?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading