简体   繁体   中英

memory leak (logic issue) in one of my features

for one of my project I have to do a function that read a whole line from a file. this one works however i've got a memory leak because of concatenateString.

Indeed, concatenateString return a string (on the heap)... So even if I free output, it will remains lots of stuff on the heap.. I dunno how to free these ones.

Is there anyone who could help me? Thank's for all!

char * readLine(FILE * fichier)
{
const int bufferSize=16;
char* buffer=(char*)calloc(bufferSize,sizeof(char));
char* output=(char*)calloc(1,sizeof(char));

while(icaseEndWith("\n",buffer)==0 && fgets(buffer,bufferSize,fichier)!=NULL)
{
    output=concatenateString(output,buffer);
}

free(buffer);
return output;
}

Thank's for everything!

the current buffer size to pass to function by pointer. (and then do realloc .)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *concatenateString(char *out, size_t *size, const char *str){
    size_t len = strlen(str);
    char *new_out = realloc(out, *size + len);
    if(new_out == NULL){
        free(out);
        perror("realloc");
        exit(EXIT_FAILURE);
    }
    *size += len;
    return strcat(new_out, str);
}
#if 0 //test code
int main(){
    char *out = calloc(1, sizeof(char));
    size_t size = 1;
    out = concatenateString(out, &size, "test1\n");
    out = concatenateString(out, &size, "test2\n");
    out = concatenateString(out, &size, "test3\n");
    printf("%s", out);
    free(out);
    return 0;
}
#end if

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM