一个类假如存在一个静态成员变量指针,在以下几种情况下动态分配内存,该如何回收内存:
1)在外部函数中动态分配内存,代码如下:
test.cpp
class Test
{
public:
static char* m_pSZ;
};
char* Test::m_pSZ = NULL;
void testAlloc()
{
Test::m_pSZ = new char[16];
}
int main()
{
testAlloc();
std::cout << "Already alloc for Test::m_pSZ!" << std::endl;
return 0;
}
通过使用g++ -g test.cpp -c test编译,再g++ -o test test.o链接成执行文件,最后通过检测内存泄漏工具valgrind检测,命令如下:
valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all ./test
检测结果如下:
==14924== Memcheck, a memory error detector
==14924== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==14924== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==14924== Command: ./test
==14924==
Already alloc for Test::m_pSZ!
==14924==
==14924== HEAP SUMMARY:
==14924== in use at exit: 16 bytes in 1 blocks
==14924== total heap usage: 1 allocs, 0 frees, 16 bytes allocated
==14924==
==14924== 16 bytes in 1 blocks are still reachable in loss record 1 of 1
==14924== at 0x402ACDB: operator new[](unsigned int) (vg_replace_malloc.c:383)
==14924== by 0x80486EE: testAlloc() (test.cpp:13)
==14924