zoukankan      html  css  js  c++  java
  • Memory Layout of C Programs

    from apue 7.6. Memory Layout of a C Program

    A typical memory representation of C program consists of following sections.

    1. Text segment
    2. Initialized data segment
        2.1 initialized read-only area
        2.2 initialized read-write area
    3. Uninitialized data segment
    4. Heap
    5. Stack

    Read Memory Layout of C Programs for more details. It's compiled from apue 7.6 with more details and examples.

    做個實驗吧

    #include<iostream>
    using namespace std;
    int main(){
        int a1,a2,a3,a4,a5;
        int *b1=new int;    //在C語言中 用的是malloc()
        int *b2=new int;
        int *b3=new int;
        int *b4=new int;
        cout << "address of a1 is " << &a1 << endl;
        cout << "address of a2 is " << &a2 << endl;
        cout << "address of a3 is " << &a3 << endl;
        cout << "address of a4 is " << &a4 << endl;
        cout << "address of a5 is " << &a5 << endl;
        cout << "address of b1 is " << &b1 << endl;
        cout << "  value of b1 is " << b1 << endl;
        cout << "address of b2 is " << &b2 << endl;
        cout << "  value of b2 is " << b2 << endl;
        cout << "address of b3 is " << &b3 << endl;
        cout << "  value of b3 is " << b3 << endl;
        cout << "address of b4 is " << &b4 << endl;
        cout << "  value of b4 is " << b4 << endl;
    
        delete b1,b2,b3,b4;
    }
    

    address of a1 is 0x7fff4e62c554
    address of a2 is 0x7fff4e62c550
    address of a3 is 0x7fff4e62c54c
    address of a4 is 0x7fff4e62c548
    address of a5 is 0x7fff4e62c544
    address of b1 is 0x7fff4e62c538
    value of b1 is 0x417a010
    address of b2 is 0x7fff4e62c530
    value of b2 is 0x417a030
    address of b3 is 0x7fff4e62c528
    value of b3 is 0x417a050
    address of b4 is 0x7fff4e62c520
    value of b4 is 0x417a070
    可以發現,a1到a5的記憶體位址是由大而小,也就是由高而低。而b1到b4的所指的位址(在heap)是由小而大,也就是由低而高,b1到b4本身的位址(在stack)則是由高而低。

    Other references:

    <<Advanced Programming in the UNIX Environment>> 7.6. Memory Layout of a C Program

    Memory layout of C process (pdf)download

    Data segment

    [0x03]. Notes on Assembly - Memory from a process' point of view

    Structure of a C-Program in Memory | How Heap,Stack,Data and Code segments are stored in memory?

  • 相关阅读:
    16解释器模式Interpreter
    15适配器模式Adapter
    14桥接模式Bridge
    13组合模式Composite
    12外观模式Facade
    11代理模式Proxy
    10享元模式Flyweight
    09观察者模式ObServer
    08策略模式Strategy
    07装饰模式Decorator
  • 原文地址:https://www.cnblogs.com/bittorrent/p/3764367.html
Copyright © 2011-2022 走看看