Still Reachable Leak detected by Valgrind

前端 未结 5 1070
南旧
南旧 2020-11-22 11:42

All the functions mentioned in this block are library functions. How can I rectify this memory leak?

It is listed under the \"Still reachable\" cat

5条回答
  •  长情又很酷
    2020-11-22 12:47

    Here is a proper explanation of "still reachable":

    "Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

    Local variables that are assigned allocations and not free'd are almost always leaks.

    Here is an example

    int foo(void)
    {
        static char *working_buf = NULL;
        char *temp_buf;
        if (!working_buf) {
             working_buf = (char *) malloc(16 * 1024);
        }
        temp_buf = (char *) malloc(5 * 1024);
    
        ....
        ....
        ....
    
    }
    

    Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

提交回复
热议问题