天天看點

distinction between heap and stack

前不久在一個部落格看到一篇文章談到 stack(棧)與heap(堆)的差別問題,stack我是知道的(廢話,學過資料結構都懂)。heap想想确實也太不清楚,于是一頓google。發現這條連結的解釋還不錯http://www.maxi-pedia.com/what+is+heap+and+stack

What is heap and stack?(原文标題)

  The stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime are stored.

What are the memory segments?

The distinction between stack and heap relates to programming. When you look at your computer memory, it is organized into three segments:

  • text (code) segment
  • stack segment
  • heap segment

  The text segment (often called code segment) is where the compiled code of the program itself resides. When you open some EXE file in Notepad, you can see that it includes a lot of "Gibberish" language, something that is not readable to human. It is the machine code, the computer representation of the program instructions. This includes all user defined as well as system functions.

Now let's get to some details.

What is stack?

  The two sections other from the code segment in the memory are used for data. The stack is the section of memory that is allocated for automatic variables within functions.

  Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is a section of memory and its associated registers that is used for temporary storage of information in which the most recently stored item is the first to be retrieved.

What is the heap?

  On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of blocks is not known until run time. Heap is usually being used by a program for many different purposes.The stack is much faster than the heap but also smaller and more expensive.

Heap and stack from programming perspective

Most object-oriented languages have some defined structure, and some come with so-called main() function. When a program begins running, the system calls the function main() which marks the entry point of the program. For example every C, C++, or C# program must have one function named main(). No other function in the program can be called main(). Before we start explaining, let's take a look at the following example:

int x;                           /* static stack storage */
void main() {   
int y;                           /* dynamic stack storage */   
char str;                      /* dynamic stack storage */   
str = malloc(50);          /* allocates 50 bytes of dynamic heap storage */   
size = calcSize(10);       /* dynamic heap storage */
           

  When a program begins executing in the main() function, all variables declared within main() will be stored on the stack.

  If the main() function calls another function in the program, for example calcSize(), additional storage will be allocated for the variables in calcSize(). This storage will be allocated in the heap memory segment.

  Notice that the parameters passed by main() to calcSize() are also stored on the stack. If the calcSize() function calls to any additional functions, more space would be allocated at the heap again.

  When the calcSize() function returns the value, the space for its local variables at heap is then deallocated and heap clears to be available for other functions.

  The memory allocated in the heap area is used and reused during program execution.

  It should be noted that memory allocated in heap will contain garbage values left over from previous usage.

  Memory space for objects is always allocated in heap. Objects are placed on the heap.

  Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.

  Even though objects are held on heap, references to them are also variables and they are placed on stack.

  The stack segment provides more stable storage of data for a program. The memory allocated in the stack remains in existence for the duration of a program. This is good for global and static variables. Therefore, global variables and static variables are allocated on the stack.

Why is stack and heap important?

  When a program is loaded into memory, it takes some memory management to organize the process. If memory management was not present in your computer memory, programs would clash with each other leaving the computer non-functional.

Heap and stack in Java

  When you create an object using the new operator, for example myobj = new Object();, it allocates memory for the myobj object on the heap. The stack memory space is used when you declare automatic variables.

  Note, when you do a string initialization, for example String myString;, it is a reference to an object so it will be created using new and hence it will be placed on the heap.

 總結一下:

預備知識:Memory segment

計算機記憶體分為三個segments:

(1)text/code segment-存放編譯後的代碼;

(2)heap segment- 一般由程式員配置設定釋放, 若程式員不釋放,程式結束時可能由OS回收 。注意它與資料結構中的堆是兩回事,配置設定方式倒是類似于連結清單;

(3)stack segment-由編譯器自動配置設定釋放 ,存放函數的參數值,局部變量的值等。其操作方式類似于資料結構中的棧。

配置設定用途:

(1)Stack: allocated for automatic variables within functions

(2)Heap: used for dynamic memory allocation

存取方式比較:

(1)Stack: 後進先出(LIFO)

(2)Heap: 随意配置設定和釋放

效率和空間比較:

The stack is much faster than the heap but also smaller and more expensive

一般對應的配置設定:

heap:

(1)main()中調用的其他函數,其他函數在調用的其他函數,都是heap

(2)objects也是heap(是以CString也是heap型)

Stack:

(1)内置資料類型(Built-in datatypes)如int,float等都是stack

(2)reference to objects是stack

(3)global variables and static variables are allocated on the stack

其他的一些總結:

http://zhidao.baidu.com/question/167720536.html

2.2 申請後系統的響應

棧:隻要棧的剩餘空間大于所申請空間,系統将為程式提供記憶體,否則将報異常提示棧溢出。

堆:首先應該知道作業系統有一個記錄空閑記憶體位址的連結清單,當系統收到程式的申請時,

會周遊該連結清單,尋找第一個空間大于所申請空間的堆結點,然後将該結點從空閑結點連結清單中删除,并将該結點的空間配置設定給程式,另外,對于大多數系統,會在這塊記憶體空間中的首位址處記錄本次配置設定的大小,這樣,代碼中的delete語句才能正确的釋放本記憶體空間。另外,由于找到的堆結點的大小不一定正好等于申請的大小,系統會自動的将多餘的那部分重新放入空閑連結清單中。

2.3申請大小的限制

棧:在Windows下,棧是向低位址擴充的資料結構,是一塊連續的記憶體的區域。這句話的意思是棧頂的位址和棧的最大容量是系統預先規定好的,在WINDOWS下,棧的大小是2M(也有的說是1M,總之是一個編譯時就确定的常數),如果申請的空間超過棧的剩餘空間時,将提示overflow。是以,能從棧獲得的空間較小。

堆:堆是向高位址擴充的資料結構,是不連續的記憶體區域。這是由于系統是用連結清單來存儲的空閑記憶體位址的,自然是不連續的,而連結清單的周遊方向是由低位址向高位址。堆的大小受限于計算機系統中有效的虛拟記憶體。由此可見,堆獲得的空間比較靈活,也比較大。

2.4申請效率的比較:

棧由系統自動配置設定,速度較快。但程式員是無法控制的。

堆是由new配置設定的記憶體,一般速度比較慢,而且容易産生記憶體碎片,不過用起來最友善.

另外,在WINDOWS下,最好的方式是用VirtualAlloc配置設定記憶體,他不是在堆,也不是在棧是直接在程序的位址空間中保留一快記憶體,雖然用起來最不友善。但是速度快,也最靈活。

2.5堆和棧中的存儲内容

棧: 在函數調用時,第一個進棧的是主函數中後的下一條指令(函數調用語句的下一條可執行語句)的位址,然後是函數的各個參數,在大多數的C編譯器中,參數是由右往左入棧的,然後是函數中的局部變量。注意靜态變量是不入棧的。

當本次函數調用結束後,局部變量先出棧,然後是參數,最後棧頂指針指向最開始存的位址,也就是主函數中的下一條指令,程式由該點繼續運作。

堆:一般是在堆的頭部用一個位元組存放堆的大小。堆中的具體内容有程式員安排。

轉載于:https://www.cnblogs.com/CHYGO/articles/1902769.html