zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    SQL 多条件查询
    android实现程序开机自启动
    SendMessage模拟按键所需的虚拟键码
    使用API进行文件读写——CreateFile,ReadFile,WriteFile等
    VB断点拷贝大文件(WIN7系统需要更改某个API函数,具体我也忘了)
    mysql
    webstorm
    ubuntu ftp服务器
    centos ftp 服务器
    nignx
  • 原文地址:https://www.cnblogs.com/eat-too-much/p/15180302.html
Copyright © 2011-2022 走看看