malloc是怎麼實現動態記憶體分配的,malloc動態記憶體分配

來源:互聯網
上載者:User

malloc是怎麼實現動態記憶體分配的,malloc動態記憶體分配

網上總結到的資訊:

(1) 靜態指派:是在棧上分配,是由使用者自己申請,是由作業系統自己釋放的

  動態分配:是由編譯器分配,作業系統沒有提供這種機制,所以自己申請,必須自己刪除!
(2)你也要明白,棧的容量非常的小,而且特別貴,不能滿足所有的記憶體申請,所以就要動態分配,
(3)動態分配是編譯器自己完成的,跟作業系統沒有關係

(4) 動態分配效率比較低,不過容量跟使用者需求有關。

(5)C語言裡面用malloc和free,C++裡面用new 和delete。

(6)malloc要求穿進去一個分配記憶體大小的參數,還怎麼動態呢?

看下面的例子:

#include <iostream>#include <string>#include <cstdlib> using namespace std;void main(){int* p;p=(int*)malloc(sizeof(int)*10);for(int i=0;i<11;i++){*(p+i)=i;}for(int i=0;i<11;i++)cout<<*(p+i)<<"   ";system("pause");}


說明:即使用malloc分配了10個int大小的空間,也可以動態給第11個int賦值,實現記憶體的動態擴充,用靜態記憶體配置int  num[10]將不能完成。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.