Linux C申請內存三種基本方式


一份代碼可以知道具體方式和原理:

int main()
{
        int stack_a;
        int stack_b;
        static int static_c;
        static int static_d;
        int *heap_e;
        int *heap_f;
        heap_e = (int *)malloc(10);
        heap_f = (int *)malloc(10);
        printf("The a address is %p\n",&stack_a);
        printf("The b address is %p\n",&stack_b);
        printf("The c address is %p\n",&static_c);
        printf("The d address is %p\n",&static_d);
        printf("The e address is %p\n",heap_e);
        printf("The f address is %p\n",heap_f);
        return 0;
}

輸出log

root@ubuntu:/home/watson/test# ./a.out 
The a address is 0x7ffd2d5894f0
The b address is 0x7ffd2d5894f4
The c address is 0x60104c
The d address is 0x601050
The e address is 0x23db010
The f address is 0x23db030

分析:

1. ab都是堆棧中的棧內存申請,因int占用四個字節,故f0 -> f4。

2. cd都是靜態存儲變量申請內存,在編譯時已經申請分配好,不釋放。

3. ef都是動態申請內存,屬於堆棧的堆內存申請,此處返回一個指針。

 

情況1

        heap_e = (int *)malloc(20); heap_f = (int *)malloc(20);
  malloc (10) -> 10bytes內存申請
 The e address is 0xc04010
 The f address is 0xc04030
|--------------------|.....|--------------------|
0xc04010
            0xc04030
中間0x20 = 32bytes,由於字節對齊,申請時需要申請20bytes,系統對malloc管理是讓其在32bytes后再開辟新的內存空間。
情況2
 
 heap_e = (int *)malloc(30);
 heap_f = (int *)malloc(30);

malloc (10) -> 10bytes內存申請
 The e address is 0xc04010
 The f address is 0xc04040
|------------------------------|.....|------------------------------|
0xc04010
                      0xc04040
中間0x30 = 48bytes,由於字節對齊,申請時需要申請30bytes,系統對malloc管理是讓其在48bytes后再開辟新的內存空間。
修改如下的程序:
        printf("The e address is %p\n",heap_e);
        printf("The e+1 address is %p\n",heap_e + 1);
        printf("The f address is %p\n",heap_f);
        printf("The f-1 address is %p\n",heap_f - 1);

    The e address is 0x12fa010
    The e+1 address is 0x12fa014
    The f address is 0x12fa030
    The f-1 address is 0x12fa02c

    0x12fa014

    0x12fa02c

    前后內存地址不一致,malloc多次內存是不會連續的。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM