C/C++動態配置記憶體_記憶體洩漏介紹

C/C++動態配置記憶體_記憶體洩漏介紹

C/C++動態配置記憶體_記憶體洩漏介紹


資料來源: https://mp.weixin.qq.com/s/WvAsjLhgGlRJsxFPLAI3lw


C code

/*
https://mp.weixin.qq.com/s/WvAsjLhgGlRJsxFPLAI3lw
https://www.tutorialspoint.com/compile_c_online.php
*/

#include <stdio.h>

int main()
{
 char arr_char[1024*1000000];
    arr_char[0] = '0';
}
/*
$gcc -o main *.c
$main
/usr/bin/timeout: the monitored command dumped core
sh: line 1: 182320 Segmentation fault      /usr/bin/timeout 10s main
*/
/*
https://mp.weixin.qq.com/s/WvAsjLhgGlRJsxFPLAI3lw
https://www.tutorialspoint.com/compile_c_online.php
*/

#include <stdio.h>
#include<string.h>
#include <malloc.h>
int main()
{
 char *p1 = (char *)malloc(1024*1000000);
 strcpy(p1, "这里是堆区");
 printf("%s\n", p1);
 free(p1);
}

/*
$gcc -o main *.c
$main
这里是堆区
*/
© 2021 GitHub, Inc.


C++ code

//https://mp.weixin.qq.com/s/WvAsjLhgGlRJsxFPLAI3lw
//https://www.tutorialspoint.com/compile_cpp_online.php

#include <iostream>

using namespace std;

class Babe
{
public:
    Babe()
    {
        cout << "Create a Babe to talk with me" << endl;
    }

    ~Babe()
    {
        cout << "Babe don\'t Go away,listen to me" << endl;
    }
};


int main()
{
    int *a = new int[10];
    for(int i=0;i<10;i++)
    {
        a[i]=i;
        cout<< a[i]<<"\t";
    }
    cout<<"\n";
    delete a;        //方式1
    //delete[] a;     //方式2

    Babe* pbabe = new Babe[3];
    delete []pbabe;//會GG的寫法-> delete pbabe;
    
    pbabe = new Babe[3];
    delete[] pbabe;
   
   return 0;
}
/*
$g++ -o main *.cpp
$main
0	1	2	3	4	5	6	7	8	9	
Create a Babe to talk with me
Create a Babe to talk with me
Create a Babe to talk with me
Babe don't Go away,listen to me
Babe don't Go away,listen to me
Babe don't Go away,listen to me
Create a Babe to talk with me
Create a Babe to talk with me
Create a Babe to talk with me
Babe don't Go away,listen to me
Babe don't Go away,listen to me
Babe don't Go away,listen to me
*/
© 2021 GitHub, Inc.

圖文版完整內容:

2 thoughts on “C/C++動態配置記憶體_記憶體洩漏介紹

  1. C/C++ 記憶體洩漏 種類 簡易文字整理

    01.動態配置記憶體,申請後忘記釋放
    02.檔案開啟,忘記關閉 [很難察覺]
    03.類別使用物件指標動態配置建立後忘記釋放物件

    1. 操作建議
      01.對於所有指標 變數 用完即立刻釋放對應記憶體

      02.如果無法在單一函數類使用完畢該變數操作,就應該將變數宣告在全域變數之中,如此才能用完即立刻釋放對應記憶體

      03. 善用IDE 經常檢查指標變數的 配置/釋放 記憶體指令應該隨時保持成對狀態

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *