[存储管理]一个c程序在内存中的映射分为哪几部分? - 拳不离手、曲不离口 - Speak with your code, my friend, not your word.
[文件管理]Almost everything in Unix can be treated as a file.
cpu什么时候由执行用户代码转入执行内核代码?

[存储管理]一个c程序在内存中的映射分为哪几部分?

clem posted @ 2009年3月20日 14:38 in Kernel , 4296 阅读

高地址(3G)

...

stack

.

.

.

heap
bss
data
rodata
text

.

.

.

低地址(0)

 

在用户存储空间,一个c程序的映射可分为6部分,代码段、常量段、数据段、bss段、堆、栈。

 

其中:

常量主要是指字符串常量;

数据是指函数外定义的、初始化过的变量;

bss是指函数外定义的、未初始化过的变量;

局部变量、子函数返回地址、传给子函数的参数都在栈中分配,方向由高地址向低地址;

动态分配的空间在堆中,方向由低地址向高地址。

 

运行以下程序,程序各部分在内存中的相对位置一目了然。

 

#include <stdio.h>
#include <malloc.h>

int i = 5, j;

void subfunc(int a)
{
    printf("arg:%p\nsubfunc:%p\n",&a, subfunc);
}

int main(void)
{
    int tmp = i - 1;
    char *p = "abcde";
    int a[5];
   
    printf("data:%p\nbss:%p\nautovar:%p\nconst:%p\narray:%p\n",\
            &i, &j, &tmp, p, &a[0]);
   
    p = malloc(sizeof(a) / sizeof(a[0]));

    for (; tmp >= 0; tmp--)
        p[tmp] = a[tmp];
 
    printf("heap:%p\nfunc:%p\n", p, main);

    subfunc(tmp);

    free(p);
    return 0;
}

 

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter