在 gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3 和 Intel(R) Core(TM)2 Duo CPU 上运行以下程序,我想验证 c 程序堆栈向下增长,我编写以下代码:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
static int a = 1;
static int b;
int c = 2;
int d;
void foo(void)
{
int *p1;
int *p2;
int *p3;
int *p4;
printf("&p1\t%p\n", &p1);
printf("&p2\t%p\n", &p2);
printf("&p3\t%p\n", &p3);
printf("&p4\t%p\n", &p4);
}
int main()
{
static int e = 3;
static int f;
int g = 4;
int h;
char *str1 = "abc";
char *str2 = "abc";
char *str3;
char *str4;
printf("&\"abc\"\t%p\n", &"abc");
printf("&str1\t%p\n", &str1);
printf("&str2\t%p\n", &str2);
printf("str1\t%p\n", str1);
printf("str2\t%p\n", str2);
printf("&str3\t%p\n", &str3);
printf("str3\t%p\n", str3);
str4 = (char *)malloc(strlen("abc")*sizeof(char));
printf("&str4\t%p\n", &str4);
printf("str4\t%p\n", str4);
printf("&g\t%p\n", &g);
printf("&h\t%p\n", &h);
foo();
return 0;
}
我得到这个结果:
&"abc" 0x8048680
&str1 0xbff1be20
&str2 0xbff1be24
str1 0x8048680
str2 0x8048680
&str3 0xbff1be28
str3 0x8048599
&str4 0xbff1be2c
str4 0x950f008
&g 0xbff1be18
&h 0xbff1be1c
&p1 0xbff1bde0
&p2 0xbff1bde4
&p3 0xbff1bde8
&p4 0xbff1bdec
我发现str1、str2、str3、str4的地址向上增长,p1、p2、p3、p4的地址也在向上增长,而不是向下增长,为什么?