简体   繁体   中英

Memory leak on returning pointer

I am facing a memory leak condition in the following functions.

char * readdatafromfile(unsigned pageNumber) {
    char *buff = (char*) malloc(sizeof(char) * pagesize);
    lseek(fd, pagesize * (pageNumber), SEEK_SET);
    read(fd, buff, pagesize);

    return buff;
}
//Read from file
char * readfromfile(char *fname, int pageno) {
    char *buff = NULL;
    fd = searchinvector(fname);
    if (fd > 0)
        buff = readdatafromfile(pageno);
    else
        printf("\nINDEX is not opened\n");
    return buff;
}

I am trying to call the function the following way

char* root_buf = readfromfile(fname,pageno);

Can someone point to me where the memory leak occurs and how to overcome it.

EDIT

I do call free(root_buf); later. Forgot to mention that part. I believe this has to do with the fact that I am creating a pointer and returning it. Maybe the reference is caught in another pointer in the caller function.

The memory allocated using malloc are never freed again. If you do this from your call site:

char* root_buf = readfromfile(fname,pageno); 
// do stuff
free(root_buf);

It should solve the leak.

You are using malloc here.

char *buff = (char*) malloc(sizeof(char) * pagesize); 

You need to free the memory after you have used it.

After you are done with root_buf and no longer need it:

free (root_buf);

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