1. "只要分配了内存没有释放,就会导致内存泄漏" -- 这是我以前的理解, 是片面的.
分配了的内存,如果它的指针没有丢失,就不算是泄漏. 一般说来,为static指针变量或全局的指针变量(它们的生存期是全局的)进行内存分配,如果没有释放它,虽然这也是"not-freed blocks",但是它是"reachable"的.现代的OS会得到这些指针并去释放它.
下面是两个例子:1) 使用全局指针或静态指针:
int main()
{
static int *pi; // use static pointer: not a real memory leak!!!
pi = new int;
return 0;
}
使用valgrind检查:
valgrind --leak-check=yes --show-reachable=yes -q ./memtest
==13764== searching for pointers to 1 not-freed blocks.
==13764== checked 4488448 bytes.
==13764==
==13764== 4 bytes in 1 blocks are still reachable in loss record 1 of 1
==13764== at 0xB74D27AB: __builtin_new (vg_replace_malloc.c:172)
==13764== by 0xB74D2802: operator new(unsigned) (vg_replace_malloc.c:185)
==13764== by 0x8048491: main (in /home/prog/valgrind/memtest)
==13764== by 0xB71C4BA6: __libc_start_main (in /lib/libc-2.3.2.so)
==13764==
==13764== LEAK SUMMARY:
==13764== definitely lost: 0 bytes in 0 blocks.
==13764== possibly lost: 0 bytes in 0 blocks.
==13764== still reachable: 4 bytes in 1 blocks.
==13764== suppressed: 0 bytes in 0 blocks.
==13764==
报告说有一个"not-freed block",但这个block是reachable的,所以它不算是真正的memory leak.
2) 如果使用的是局部指针:
int main()
{
int *pi; // use local pointer: real memory leak!!!
pi = new int[100];
return 0;
}
==13782== searching for pointers to 1 not-freed blocks.
==13782== checked 4484352 bytes.
==13782==
==13782== 4 bytes in 1 blocks are definitely lost in loss record 1 of 1
==13782== at 0xB74D27AB: __builtin_new (vg_replace_malloc.c:172)
==13782== by 0xB74D2802: operator new(unsigned) (vg_replace_malloc.c:185)
==13782== by 0x8048491: main (in /home/prog/valgrind/memtest)
==13782== by 0xB71C4BA6: __libc_start_main (in /lib/libc-2.3.2.so)
==13782==
==13782== LEAK SUMMARY:
==13782== definitely lost: 4 bytes in 1 blocks.
==13782== possibly lost: 0 bytes in 0 blocks.
==13782== still reachable: 0 bytes in 0 blocks.
==13782== suppressed: 0 bytes in 0 blocks.
==13782==
报告说是"definitely lost",这才是真正的memory leak!
切记:静态变量只能由静态函数访问。