C++ delete [] 与 delete
生活随笔
收集整理的這篇文章主要介紹了
C++ delete [] 与 delete
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡介
對于普通數據類型數組 使用 delete [] pa 和 delete pa, 都不會產生內存泄露. 對于自己定義的對象數組, 會產生內存泄露.
環境
g++ , valgrind 來查看是否產生了內存泄露
參考鏈接
https://www.cnblogs.com/sura/archive/2012/07/03/2575448.html
code
#include <iostream>
#include <ctime>
#include <algorithm>
#include <stdlib.h>
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <limits>
#include <stack>
#include <list>
#include <queue>
using LL = long long;
using ULL = unsigned long long;
//using PII = pair<int,int>;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
using namespace std;
// 大于等于k的最小整數
class Test{
public:
int a;
Test() {
a = 0;
}
~Test(){
cout << "~Test()" << endl;
}
};
int main() {
int *p = new int[5];
cout << sizeof(p) << endl;
delete p;
int *pa = new int[5];
cout << sizeof(pa) << endl;
delete [] pa;
Test *pb = new Test[5];
cout << sizeof(pb) << endl;
delete [] pb;
Test *pc = new Test[5];
cout << sizeof(pc) << endl;
delete pc; // 會導致內存泄露 且出現段錯誤 segmentation fault (core dumped)
/*
==207912== LEAK SUMMARY:
==207912== definitely lost: 28 bytes in 1 blocks
==207912== indirectly lost: 0 bytes in 0 blocks
==207912== possibly lost: 0 bytes in 0 blocks
==207912== still reachable: 0 bytes in 0 blocks
==207912== suppressed: 0 bytes in 0 blocks
*/
return 0;
}
TIP
這里顯示的sizeof都是8顯示的都是指針的大小. 因為是64位系統, 使int達到了8個字節的長度.
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
總結
以上是生活随笔為你收集整理的C++ delete [] 与 delete的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java怎么插入oracle数据库tim
- 下一篇: svn 添加目录 linux,linux