Search code examples
cmemory-leaksbufferdynamic-arrays

Memory leak / not properly freeing. How to fix?


I am partially reading input into a buffer in a function and then freeing it in main() but it doesn't seem to be working. My code:

char *save_to_buff()
{
    int fd = 0; // set read() to read from STDIN_FILENO, because it's number is 0
    const size_t read_size = 100; // set chunk size
    size_t size = read_size;
    char *buff = malloc(size+1);
    size_t offset = 0;
    size_t res = 0;
    while((res = read(fd, buff + offset, read_size)) > 0) // partial read from stdin and save to buff
    {
        if(res == -1) // check for read errors
        {
            read_error();
            free(buff);
            return NULL;
        }
        
        offset += res;
        if (offset + read_size > size)
        {
            size *= 2;
            buff = realloc(buff, size+1);
        }
        buff[offset] = '\0';
    }
    return buff;
}

main:

char *buff = save_to_buff();
// do sth
free(buff);

Valgrind result

Edit: just tried it with a 1 byte read and not a partial read and there is no memory leak.


Solution

  • According to this answer to a post, still reachable does not necessarily indicate a memory leak.