内存泄露例子

valgrind --tool=memcheck --leak-check=full path



int main()
{
int *p1= new int;
char * p2 = new char[10];

//delete p1; //4 bytes in 1 blocks are definitely lost in loss record 1 of 1
//delete p2; //10 bytes in 1 blocks are definitely lost in loss record 1 of 1
return 0;
}


delete p2 : 错误的释放方式
Mismatched free() / delete / delete []
==14638==    at 0x4A05A33: operator delete(void*) (vg_replace_malloc.c:346)
==14638==    by 0x40065D: main (test1.cpp:7)
==14638==  Address 0x512e090 is 0 bytes inside a block of size 10 alloc'd
==14638==    at 0x4A065BA: operator new[](unsigned long) (vg_replace_malloc.c:264)
==14638==    by 0x400647: main (test1.cpp:4)



应该为delete []p2

使用 new 得来的空间,必须用 delete 来释放;使用 new [] 得来的空间,必须用 delete [] 来释放。彼此之间不能混用。用 new [] 分配出连续空间后,指针变量“指向”该空间的首地址。
g++ -g test1.cpp -o test
valgrind --tool=memcheck --leak-check=full ./test

你可能感兴趣的:(内存泄露)