C++拾遺--malloc free與new delete的同與不同,--mallocdelete

來源:互聯網
上載者:User

C++拾遺--malloc free與new delete的同與不同,--mallocdelete

                   C++拾遺--malloc free與new delete的同與不同

前言

    在C中我們常使用malloc和free來動態分配與釋放記憶體,在C++中對應的是new和delete。這裡我們來探討下他們的同與不同。

本文1.內建類型

對相同的代碼進行調試,查看記憶體

#include <iostream>using namespace std;int main(){int *p = (int*)malloc(sizeof(int) * 10);cout << p << endl;//斷點for (int i = 0; i < 10; i++)p[i] = i;//斷點free(p);//斷點cin.get();return 0;}

調試



同樣的功能使用new和delete來操作

#include <iostream>using namespace std;int main(){int *p = new int[10];cout << p << endl;<span style="white-space:pre"></span>//斷點for (int i = 0; i < 10; i++)p[i] = i;<span style="white-space:pre"></span>//斷點delete[]p;<span style="white-space:pre"></span>//斷點cin.get();return 0;}
調式



對於內建類型,兩組操作的效果是一樣的。


2.類類型代碼一

#include <iostream>using namespace std;class MyClass{public:MyClass(){cout << "MyClass create" << endl;}~MyClass(){cout << "MyClass delete" << endl;}};int main(){MyClass *p1 = (MyClass *)malloc(sizeof(MyClass));free(p1);cout << "--------------------" << endl;MyClass *p2 = new MyClass;delete p2;cin.get();return 0;}
運行


malloc 只是分配了記憶體,而new 不僅分配了記憶體,還調用了建構函式。

free 只是釋放了記憶體,而delete不僅釋放了記憶體,還調用了解構函式。


代碼二

#include <iostream>#include <new>using namespace std;class MyClass{public:int *p;MyClass(){//分配400M記憶體p = new int[1024 * 1024 * 100];cout << "MyClass create" << endl;}~MyClass(){delete[]p;cout << "MyClass delete" << endl;}};int main(){MyClass *p1 = (MyClass *)malloc(sizeof(MyClass));//斷點free(p1);//斷點MyClass *p2 = new MyClass;//斷點delete p2;//斷點cin.get();return 0;}
啟動工作管理員,查看記憶體消耗

malloc free



new delete



由於malloc只是給變數p本身分配了記憶體,但由於不調用建構函式,所以無法讓p指向一片分配的記憶體。同理,free只是釋放了變數p,由於並不調用解構函式,所以無法釋放p指向的記憶體。





本專欄目錄

  • C++拾遺 目錄

所有內容的目錄

  • CCPP Blog 目錄




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.