進程內存佈局

一個由 C/C++編譯的程序佔用的內存(memory)分爲以下幾個部分:

1. 程序代碼區(.text)  -      存放函數體的二進制代碼  。

2. 文字常量區(.rodata)     -      常量字符串就是放在這裏的,程序結束後由系統釋放(rodata—read only data)。

3. 全局區/靜態區(static)   -      全局變量 和 靜態變量的存儲是放在一塊的。初始化的全局變量和靜態變量在一塊區域(.rwdata or .data),未初始化的全局變量和未初始化的靜態變量在相鄰的另一塊區域(.bss), 程序結束後由系統釋放。

*在 C++中,已經不再嚴格區分bss data了,它們共享一塊內存區域

4. 堆區(heap)    -      一般由程序員分配釋放(new/malloc/calloc delete/free),若程序員不釋放,程序結束時可能由 OS 回收。

注意:它與數據結構中的堆是兩回事,但分配方式倒類似於鏈表。

5. 棧區(stack)   -      由編譯器自動分配釋放,存放函數的參數值,局部變量的值等。其操作方式類似於數據結構中的棧。


(圖出自:http://www.tenouk.com/Bufferoverflowc/Bufferoverflow1c.html



(圖出自:APUE-2e, http://infohost.nmt.edu/~eweiss/222_book/222_book.html


 The computer program memory is organized into the following:

Code segment(text segment)
Data Segment 
– Data (rodata + rwdata)
– BSS
– Heap
Stack Segment


Data

The data area contains global and staticvariables used by the program that are initialized. This segment can be furtherclassified into initialized read-only (rodata) area and initialized read-writearea (rwdata).

BSS

The BSS segment also known as uninitialized datastarts at the end of the data segment and contains all uninitialized globalvariables and static variables that are initialized to zero by default. 

Heap

The heap area begins at the end of the BSSsegment and grows to larger addresses from there. The heap area is managed bymalloc/calloc/realloc/new and free/delete, which may use the brk and  sbrk system calls to adjust its size. The heaparea is shared by all shared libraries and dynamically loaded modules in aprocess.

Stack

The stack is a LIFO structure, typically locatedin the higher parts of memory. It usually “grows down” with everyregister, immediate value or stack frame being added to it. A stack frameconsists at minimum of a return address

 

例子程序

  1. //main.cpp  
  2. int a = 0;                      // 全局初始化區(data)  
  3. char *p1;                       // 全局未初始化區(bss)  
  4. int main()  
  5. {  
  6.     int b;                      // 棧區(stack)  
  7.     char s[] = “abc”;           // 棧區(stack)  
  8.     char *p2;                   // 棧區(stack)  
  9.     char *p3 = “123456”;        // p3 在棧區(stack);   “123456\0” 在常量區(rodata)  
  10.     static int c =0;            // 全局/靜態 初始化區  (data)  
  11.     p1 = (char *)malloc(10);  
  12.     p2 = (char *)malloc(20);    // 分配得來的 10 和 20 字節的區域就在堆區 (heap)  
  13.     strcpy(p1, ”123456”);       // “123456\0” 放在常量區(rodata). 編譯器可能會將它與 p3 所指向的”123456\0”優化成一個地方。  
  14.     return 0;  
  15. }   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章