C使用Valgrind解决内存泄漏问题

时间:2014-05-05 05:38:44

标签: c memory-leaks valgrind

所以我有一个php,ruby和python背景,并开始使用C.我正在使用Valgrind检查我的程序是不是在做傻事,但我经常得到这种输出:

14072== <...VALGRIND HEADER & COPYRIGHT...>
14158== HEAP SUMMARY:
14158==     in use at exit: 137,084 bytes in 196 blocks
14158==   total heap usage: 247 allocs, 51 frees, 149,496 bytes allocated
14158== 
14158== 7 bytes in 1 blocks are definitely lost in loss record 3 of 74 at
14158==    0x4C2745D: malloc in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so
14158==    by 0x50F3369: strdup in /usr/lib64/libc-2.18.so
14158==    by 0x4E51B34: readline in /usr/lib64/libedit.so.0.0.43
14158==    by 0x40083C: main in /home/<program location>/
14158== 
14158== LEAK SUMMARY:
14158==    definitely lost: 7 bytes in 1 blocks
14158==    indirectly lost: 0 bytes in 0 blocks
14158==      possibly lost: 0 bytes in 0 blocks
14158==    still reachable: 137,077 bytes in 195 blocks
14158==         suppressed: 0 bytes in 0 blocks
14158== Reachable blocks (those to which a pointer was found) are not shown.
14158== To see them, rerun with: --leak-check=full --show-leak-kinds=all
14158== 
14158== For counts of detected and suppressed errors, rerun with: -v
14158== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 2 from 2)

这个valgrind调试输出来自这个快速REPL,只是在屏幕上回叫用户输入,或者在输入等于:exit时退出:

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

#include <editline/readline.h>

static char prompt[5]   = "repl>";
static char* cmd_exit = ":exit";

int main(int argc, char** argv) {

    puts("Press Ctrl+c to Exit\n");

    while(1) {
        char* input = readline(prompt);
        add_history(input);
        if(strcmp(input,cmd_exit) == 0) {
            puts("Bye!");
            return 0;
        }
        printf("%s\n", input);
        free(input);
    }
    return 0;
}

我已经尝试在函数main返回一个值之前释放promptcmd_exit变量,但根据Valgrind仍然存在泄漏。

...
    free(prompt);
    free(cmd_exit);
    return 0;
}

有些问题:

  • 如何摆脱这种报告的内存泄漏?
  • 在这种情况下我应该使用静态变量吗?
  • 我也应该释放这些静态变量吗?

欢迎任何好的建议或材料。

1 个答案:

答案 0 :(得分:4)

您只需要free mallocinput的内容,因此您不需要释放静态变量。

由于您的readline函数似乎使用strdup且使用malloc / calloc,因此您需要释放if(strcmp(input,cmd_exit) == 0) { puts("Bye!"); free(input); return 0; } 。你在循环中这样做很好,但是当你退出循环时你错过了它:

static char prompt[6]   = "repl>";

顺便说一下:

{{1}}

文字&#34; repl&gt;&#34;有6个字符,r,e,p,l,&gt;和一个用于标记字符串结尾的空字节。