C/C++的内存泄漏检测工具Valgrind memcheck的使用经历(求大神解答疑惑,找出内存泄露真凶)(四)

2014-11-24 10:54:32 · 作者: · 浏览: 6
accept_states[s] = NULL;
}
}
DFA::~DFA() {
for (int i = 0; i < _size; i++) {
if (accept_states[i]) {
printf("delete dfa.\n");
delete accept_states[i];
accept_states[i] = NULL;
}
}
delete[] accept_states;
}
void DFA::add_state(int index, char *s) {
accept_states[index] = new accept_pair(true, true);
accept_states[index]->app_name = new char[strlen(s) + 1];
memcpy(accept_states[index]->app_name, s, strlen(s) + 1);
}
void DFA::add_size(int size) {
// reallocate memory for accept_states.
accept_pair **tmp_states = new accept_pair*[size + _size];
for (int s = 0; s < size + _size; s++)
tmp_states[s] = new accept_pair(false, false);
for (int s = 0; s < _size; s++) {
tmp_states[s]->is_accept_state = accept_states[s]->is_accept_state;
tmp_states[s]->is_strict_end = accept_states[s]->is_strict_end;
if (accept_states[s]->app_name != NULL) {
tmp_states[s]->app_name = new char[strlen(accept_states[s]->app_name) + 1];
memcpy(tmp_states[s]->app_name, accept_states[s]->app_name, strlen(accept_states[s]->app_name) + 1);
}
}
// free old memory.
for (int s = 0; s < _size; s++) {
if (accept_states[s] != NULL) {
delete accept_states[s];
accept_states[s] = NULL;
}
}
_size += size;
delete []accept_states;
accept_states = tmp_states;
}
复制代码
虽然有点长,但逻辑很简单,其中add_size()首先分配一个更大的accept_pair数组,将已有的数据全部拷贝进去,然后释放掉原来的accept_pair数组所占空间,最后将旧的数组指针指向新分配的内存空间。这是个demo程序,在我看来这段程序是没有任何内存泄露问题的,因为申请的所有内存空间最后都会在DFA析构函数中得到释放。但是Valgrind的检测报告却报出了1个内存泄露问题(红色的是程序输出):
复制代码
==3093== Memcheck, a memory error detector
==3093== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==3093== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==3093== Command: ./test
==3093==
delete accept_pair.
delete accept_pair.
delete accept_pair.
app_name: Alexia
size: 5
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
delete dfa.
delete accept_pair.
==3093==
==3093== HEAP SUMMARY:
==3093== in use at exit: 16 bytes in 2 blocks
==3093== total heap usage: 21 allocs, 19 frees, 176 bytes allocated
==3093==
==3093== 16 bytes in 2 blocks are definitely lost in loss record 1 of 1
==3093== at 0x402BE94: operator new(unsigned int) (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==3093== by 0x8048A71: DFA::add_size(int) (in /home/hadoop/test/test)
==3093== by 0x8048798: main (in /home/hadoop/test/test)
==3093==
==3093== LEAK SUMMARY:
==3093== definitely lost: 16 bytes in 2 blocks
==3093== indirectly lost: 0 bytes in 0 blocks
==3093== possibly lost: 0 bytes in 0 blocks
==3093== still reachable: 0 bytes in 0 blocks
==3093== suppressed: 0 bytes in 0 blocks
==3093==
==3093== For counts of detected and suppressed errors, rerun with: -v
==3093== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)