C中的内存分配过程?是自上而下还是自下而上的方法

时间:2014-01-23 06:37:11

标签: c++ c pointers memory allocation

#include<stdio.h> 
int main() 
{
    int a,b,*p,*q; 
    a=10; b=5; p=&a; q=&b; 
    float c=3.4, d=4.3, *r,*t;
    r=&c; t=&d; 
    char s='o'; 
    printf("address of a=%u\n",p); 
    printf("address of b=%u\n",q);
    printf("address of c=%u\n",r); 
    printf("address of d=%u\n",t); 
    printf("address of s=%u\n",&s); 
    return 0; 
}

使用这些代码输出,如

address of a=1999992860
address of b=1999992856
address of c=1999992852
address of d=1999992848
address of s=1999992847

如果内存分配是自上而下的方法,那么怎么能'd'将1个字节作为浮点变量?

如果它是自下而上的方法,实际上没有采取,那就没关系。

现在,如果我认为自下而上的方法已经完成,那么通过更改代码char s='o'

在初始化int a,b之前,它会给出一些不同的结果。

address of `a=2987907272`
address of `b=2987907268`
address of `c=2987907264`
address of `d=2987907260`
address of `s=2987907279`

请帮忙。

2 个答案:

答案 0 :(得分:4)

我认为您在询问报告的变量地址是起始地址还是结束地址。这是前者,一个起始地址。对象在连续增加地址时占用字节。

但是,请注意,Holy Standard不会将对象限制在连续的字节中,而是会讨论存储的 region ,尤其是为了支持多个虚拟继承,可以不连续的。

但实际上,大多数派生的对象占用了连续的存储空间。

答案 1 :(得分:1)

在第一个输出中,变量s在1999992847占用1个字节。变量d占用从1999992848开始直到1999992851的字节范围。

在任何情况下,您都应该始终将分配的地址视为一些魔法的结果。编译器完全可以自由地重新排序变量,按顺序分配它们,应用填充等等。

<强>更新

变量的地址始终是其区域的开头。无论分配方向如何。

             +----------------------+
1999992847:  |       s              |
             +----------------------+
1999992848:  |       d              |
1999992849:  |                      |
1999992850:  |                      |
1999992851:  |                      |
             +----------------------+
1999992852:  |       c              |
1999992853:  |                      |
1999992854:  |                      |
1999992855:  |                      |
             +----------------------+
1999992856:  |       b              |
1999992857:  |                      |
1999992858:  |                      |
1999992859:  |                      |
相关问题