【问题标题】:Memory leak with dynamic string动态字符串的内存泄漏
【发布时间】:2014-01-05 13:13:13
【问题描述】:

所以基本上我的输入是一个未知大小的字符串。 我所做的是创建一个函数来扫描它并为每个字符动态分配内存。

char* GetUnknownStr(){
char* string = NULL;
char input = 0;
int charCount = 0;
//scan for chars until ENTER is pressed
while (input != '\n'){
    scanf("%c", &input);
    //on last iteration (when ENTER is pressed) break from loop
    if (input == '\n')
        break;
    //realloc new amount of chars
    string = (char*)realloc(string, (++charCount)*sizeof(char));
    //check if realloc didnt fail
    if (string == NULL){
        puts("failed to allocate");
        return 0;
    }
    //assign char scanned into string
    string[charCount-1] = input;
}
//realloc 1 more char for '\0' in the end of string
string = (char*)realloc(string, (++charCount)*sizeof(char)); <--leak
string[charCount-1] = '\0';
return string;
}

VALGRIND:

==30911== HEAP SUMMARY:
==30911==     in use at exit: 4 bytes in 1 blocks
==30911==   total heap usage: 7 allocs, 6 frees, 16 bytes allocated
==30911== 
==30911== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==30911==    at 0x4A05255: realloc (vg_replace_malloc.c:476)
==30911==    by 0x40091F: GetUnknownStr (in /u/stud/krukfel/C/e5/a.out)
==30911==    by 0x40266B: main (in /u/stud/krukfel/C/e5/a.out)
==30911== 
==30911== LEAK SUMMARY:
==30911==    definitely lost: 4 bytes in 1 blocks
==30911==    indirectly lost: 0 bytes in 0 blocks
==30911==      possibly lost: 0 bytes in 0 blocks
==30911==    still reachable: 0 bytes in 0 blocks
==30911==         suppressed: 0 bytes in 0 blocks
==30911== 
==30911== For counts of detected and suppressed errors, rerun with: -v
==30911== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 6 from 6)

由于某种原因,我遇到了内存泄漏,无法弄清楚原因,尝试使用 valgrind 但无法从中获得太多意义。 谢谢!

【问题讨论】:

  • Valgrind 告诉你什么?
  • 你怎么知道你有泄密?

标签: c string memory memory-leaks


【解决方案1】:

除了小的风格问题,例如转换malloc 和乘以sizeof(char),你的代码没问题。实际泄漏在调用您的函数的代码中。

处理内存泄漏的一个核心问题是所有权问题。一旦您知道谁拥有分配的内存块,您就知道需要在哪里释放它以避免泄漏。在这种情况下,字符串是在GetUnknownStr 中创建的,但随后该字符串的所有权将转移给调用者。 GetUnknownStr 函数的调用者负责根据函数返回的结果调用 free。如果调用者没有释放字符串,则会报告泄漏。泄漏的位置将是上次重新分配的点,即您在代码中标记的行。

【讨论】:

  • 好吧,基本上发生的事情是我用它来扫描一个字符串(主要),然后立即释放它。
  • @FelixKreuk 看起来调用者(即你的main)跳过了对free字符串的这些调用之一。如果这是执行realloc 的唯一函数,那么看起来您已经调用了它七次。上一次用户输入三个字母(也许是“再见”命令?),此时main 退出而不调用free
猜你喜欢
  • 2014-04-30
  • 2011-08-29
  • 2013-04-03
  • 2011-06-12
  • 2018-12-17
  • 2013-12-03
  • 2011-05-04
  • 2011-08-29
  • 1970-01-01
相关资源
最近更新 更多