【问题标题】:Why do I get memory leak?为什么会出现内存泄漏?
【发布时间】:2018-09-17 00:13:53
【问题描述】:

考虑以下代码: #包括 #包括

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);
   str = NULL;

   free(str);

   return(0);
}

为什么上面的程序会导致内存泄漏?我该如何避免这种情况?

认为“str = NULL;”中发生了错误。为什么?

valgrind 日志:

==4143== Memcheck, a memory error detector
==4143== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4143== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4143== Command: ./a.out
==4143== 
String = tutorialspoint,  Address = 86097984
==4143== 
==4143== HEAP SUMMARY:
==4143==     in use at exit: 15 bytes in 1 blocks
==4143==   total heap usage: 2 allocs, 1 frees, 1,039 bytes allocated
==4143== 
==4143== 15 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4143==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4143==    by 0x1086EB: main (in /home/stack/a.out)
==4143== 
==4143== LEAK SUMMARY:
==4143==    definitely lost: 15 bytes in 1 blocks
==4143==    indirectly lost: 0 bytes in 0 blocks
==4143==      possibly lost: 0 bytes in 0 blocks
==4143==    still reachable: 0 bytes in 0 blocks
==4143==         suppressed: 0 bytes in 0 blocks
==4143== 
==4143== For counts of detected and suppressed errors, rerun with: -v
==4143== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

【问题讨论】:

  • 你为什么有str = NULL; 行呢?你觉得它有什么作用?

标签: memory memory-leaks null


【解决方案1】:

free(str);释放str指向的空间,其中str是malloc获得的空间。由于str = NULL; 行发生在free 之前,free 正试图释放位置0 的内存位置。根据 C 标准中的定义,这没有任何作用。通常在删除后设置指向0 的指针,这样如果不小心再次尝试删除它,什么也不会发生。

要修复您的代码,您只需交换行 str = NULL;free(str);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 2011-10-25
    • 1970-01-01
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多