为什么会出现内存泄漏?

时间:2018-09-17 00:13:53

标签: memory memory-leaks null

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

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)

1 个答案:

答案 0 :(得分:1)

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

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