繁体   English   中英

C用Valgrind解决内存泄漏

[英]C solving memory leaks using 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;
}

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

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

一些问题:

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

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

你只需要free的东西,你malloc版,这样你就不会需要释放的静态变量。

由于您的readline函数似乎使用了strdup并且使用了malloc / calloc,因此您需要释放input 您可以在循环中执行此操作,但这很好,但是退出循环时却错过了它:

if(strcmp(input,cmd_exit) == 0) {
        puts("Bye!");
        free(input); 
        return 0;
    }

顺便说说:

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

文本“ repl>”具有6个字符,即r,e,p,l,>和一个nul字节,用于标记字符串的结尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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