(visual)c++ 內存分配

“燙”和“屯”

在vc++中,棧中未初始化的內存在變量監視窗口總是顯示爲一串“燙”字;而堆中未初始化的內存則顯示一串“屯”字。

原因是:vc++編譯器對棧中未初始化的內存默認設置爲0xcc,而兩個0xcc,即0xcccc在GBK編碼中就是“燙”;而堆中未初始化的內存默認設置爲0xcd,而0xcdcd在GBK編碼中則是“屯”。

內存分配方式

程序運行時,首先要被加載到內存,程序在內存中的佈局大致如下圖:

代碼區存放程序的執行代碼。

數據區存放全局數據、常量、靜態變量,所以在c++中數據區又可分爲自由存儲區(自由存儲區是那些由malloc等分配的內存塊,它和堆十分相似,不過它是由free來釋放的)、全局/靜態存儲區、常量存儲區。

堆區提供動態內存,供程序隨機申請。程序員通過new操作符從堆上申請內存,通過delete操作符釋放動態申請的堆內存。如果由new動態申請的內存在使用完之後沒有釋放,則此塊內存無法再次分配,這種情況稱之爲內存泄露(memory leak)。沒有釋放的堆內存,直到整個程序結束運行之後,由操作系統自動回收。

棧區存放局部數據,如函數參數、函數內的局部變量等。函數執行結束時,局部數據佔用的棧內存被自動釋放。棧是機器系統提供的數據結構,計算機會在底層對棧提供支持:它會分配專門的寄存器(如SP)存放棧的地址,而且壓棧出棧由專門的指令來執行,所以對棧的操作效率會比較高。但是棧區的容量有限。

四個區中,除代碼區之外的三個區都可以在編程中由程序員控制使用。

堆與棧的區別

(1)堆內存在使用時由程序員負責申請和釋放,棧內存由編譯器自動管理。

(2)在32位系統下,堆內存可以達到4G,基本無限制。棧內存有大小限制且通常很小,比如vc++編譯器默認的線程棧大小爲1M。

(3)對於堆內存,頻繁申請釋放會造成內存空間不連續,產生內存碎片使程序效率降低。棧則不會。

(4)堆內存地址向上(高地址方向)生長,棧內存地址向下生長。

(5)棧內存分配和操作效率高於堆內存。

vc++編譯器設置堆棧大小

以vc2008爲例,Properties->Linker->System->Heap Reserve SizeHeap Commit SizeStack Reserve SizeStack Commit Size。msdn中關於此4個參數的解釋如下:(此4個參數設置爲0,表示使用默認值)

/HEAP:reserve[,commit]

  The /HEAP option sets the size of the heap in bytes. This option is only for use when building an .exe file.

  The reserve argument specifies the total heap allocation in virtual memory. The default heap size is 1 MB. The linker rounds up the specified value to the nearest 4 bytes.

  The optional commit argument is subject to interpretation by the operating system. In Windows NT/Windows 2000, it specifies the amount of physical memory to allocate at a time. Committed virtual memory causes space to be reserved in the paging file. A higher commit value saves time when the application needs more heap space, but increases the memory requirements and possibly the startup time.

/STACK:reserve[,commit]

  The /STACK option sets the size of the stack in bytes. Use this option only when you build an .exe file.

  The reserve value specifies the total stack allocation in virtual memory. For x86 and x64 machines, the default stack size is 1 MB. On the Itanium chipset, the default size is 4 MB.

  commit is subject to interpretation by the operating system. In Windows NT and Windows 2000 it specifies the amount of physical memory to allocate at a time. Committed virtual memory causes space to be reserved in the paging file. A higher commit value saves time when the application needs more stack space, but increases the memory requirements and possibly the startup time. For x86 and x64 machines, the default commit value is 4 KB. On the Itanium chipset, the default value is 16 KB.

【學習資料】 《編寫高質量代碼 c++》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章