Ash*_*ary 5 c pointers pointer-address
为什么返回的指针地址的十六进制值总是按降序排列?例如在这里int a被宣布之前int d,所以它的地址总是出来是大于d,和同为&b,&e和&c,&f我想知道,这是一个固定的行为,或者是这个编译器相关的?我正在使用gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-1)
#include<stdio.h>
int main(void){
int a=1;
int d=1;
char b='a' ;
char e='a';
float c=1.0;
float f=1.0;
printf("a=%p\nd=%p\nb=%p\ne=%p\nc=%p\nf=%p\n",&a,&d,&b,&e,&c,&f);
if (&a>&d)
printf("&a>&d\n");
else
{printf("&a<&d");
}
if (&a>&d && &b>&e && &c>&f)
printf("addresses are in descending order");
else{
printf("false");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
a=0xbfc6bd98 //a>d
d=0xbfc6bd94
b=0xbfc6bd9f //b>e
e=0xbfc6bd9e
c=0xbfc6bd90 //c>f
f=0xbfc6bd8c
&a>&d
addresses are in descending order
Run Code Online (Sandbox Code Playgroud)
PS:我是c的新手
在Aleph One的Smashing The Stack For Fun和Profit中找到了这个很好的解释.提取了最相关的部分.
Run Code Online (Sandbox Code Playgroud)/------------------\ lower | | memory | Text | addresses | | |------------------| | (Initialized) | | Data | | (Uninitialized) | |------------------| | | | Stack | higher | | memory \------------------/ addresses Fig. 1 Process Memory Regions
[...]
Run Code Online (Sandbox Code Playgroud)The stack consists of logical stack frames that are pushed when calling a function and popped when returning. A stack frame contains the parameters to a function, its local variables, and the data necessary to recover the previous stack frame, including the value of the instruction pointer at the time of the function call. Depending on the implementation the stack will either grow down (towards lower memory addresses), or up. In our examples we'll use a stack that grows down. This is the way the stack grows on many computers including the Intel, Motorola, SPARC and MIPS processors.
[...]
Run Code Online (Sandbox Code Playgroud)Let us see what the stack looks like in a simple example: example1.c: ------------------------------------------------------------------------------ void function(int a, int b, int c) { char buffer1[5]; char buffer2[10]; } void main() { function(1,2,3); } ------------------------------------------------------------------------------
[...]
Run Code Online (Sandbox Code Playgroud)With that in mind our stack looks like this when function() is called (each space represents a byte): bottom of top of memory memory buffer2 buffer1 sfp ret a b c <------ [ ][ ][ ][ ][ ][ ][ ] top of bottom of stack stack
如您所见,新的(本地)变量被推到堆栈顶部.根据体系结构的设计,堆栈会朝着更高的内存地址或更低的内存地址增长,后者就是你的情况.
从C语言规范的角度来看,未指定随后分配的变量的存储器位置的顺序.因此,这取决于......