动态分配内存问题
1)分配不成功,分配完必须检查是否为空
2)分配完未释放
3)越界访问分配的动态内存
4)访问已经释放的动态内存
5)double释放某块内存
example1
#include <iostream>
using namespace std;
int main()
{
int * a= (int *)malloc(2*sizeof(int));
for(int i=0; i<=2; i++)
{
a[i] = i;
cout<<a[i]<<endl;
}
free(a);
return 0;
}
1) mcheck
which mcheck
/usr/bin/mcheck
[yqiu@shn-devwr2-1 DAMIssue]$ g++ -g3 main.cpp -lmcheck
[yqiu@shn-devwr2-1 DAMIssue]$ ./a.out
0
1
2
memory clobbered past end of allocated block
Aborted
examle2 //main1.cpp
#include <iostream>
using namespace std;
int main()
{
int * a= (int *)malloc(2*sizeof(int));
for(int i=0; i<=1; i++)
{
a[i] = i;
cout<<a[i]<<endl;
}
free(a);
free(a);
return 0;
}
[yqiu@shn-devwr2-1 DAMIssue]$ g++ -g3 main1.cpp -lmcheck
[yqiu@shn-devwr2-1 DAMIssue]$ ./a.out
0
1
block freed twice
Aborted