【发布时间】:2015-10-22 23:25:34
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
int foo; /* a staticly allocated variable */
int recur(int i) { /* a recursive function */
int j = i; /* a stack allocated variable within a recursive function */
printf("recur call (i)%d: stack@ %lx\n", i, (long unsigned int) &j); /* fix this so it print
s the address of j */
if (i > 0) {
return recur(i-1);
}
return 0;
}
int stuff = 7; /* a statically allocarted, pre-initialized variable */
int main (int argc, char *argv[]) {
int i; /* a stack allocated variable */
char *buf1 = malloc(100); /* dynamically allocate some stuff */
char *buf2 = malloc(100); /* and some more stuff */
char *buf3 = malloc(100); /* and some more stuff */
printf("_main @ %lx\n", (long unsigned int) &main); /* fix to print address of main */
printf("_recur @ %lx\n", (long unsigned int) &recur); /* fix to print address of recur */
printf("main call (i):stack@ %lx\n", (long unsigned int) &i); /* fix to get address of the s
tack variable */
printf("_static foo: %lx\n", (long unsigned int) &foo); /* fix to get address of the static v
ariable */
printf("_static stuff: %lx\n", (long unsigned int) &stuff); /* fix to get address of a stati
c variable */
printf("Heap: malloc 1: %lx\n", (long unsigned int) buf1);
printf("Heap: malloc 2: %lx\n", (long unsigned int) buf2);
printf("Heap: malloc 3: %lx\n", (long unsigned int) buf3);
recur(3);
return 0;
}
这个程序的输出结果是:
_main @ 4005c2
_recur @ 40057d
main call (i):stack@ 7fff26397694
_static foo: 601050
_static stuff: 601048
Heap: malloc 1: 1862010
Heap: malloc 2: 1862080
Heap: malloc 3: 18620f0
recur call (i)3: stack@ 7fff2639766c
recur call (i)2: stack@ 7fff2639763c
recur call (i)1: stack@ 7fff2639760c
recur call (i)0: stack@ 7fff263975dc
谁能解释下?
- 为什么地址是不同的字节,例如。 main、recur 和 static_varibale 地址为 6*4=24 字节,堆为 7*4=28 字节,栈为 12*4=48 字节地址。
- 虽然我为每个 malloc 分配 100 个字节,但 malloc 1 和 malloc 2 地址之间的差异是 0x70 = 112 个字节
- 为什么 foo 和 stuff 的地址之间存在 0x601050 - 0x601048 = 8 的差异,尽管它们都是 int 并且 int 只需要 4 个字节?
【问题讨论】:
-
对齐,也许???
-
旁注:对于函数名,与静态分配的数组一样,不需要使用
&来获取地址(例如main和&main必须是相同的值) . -
另外,“recur”的堆栈帧恰好是 0x30=48 字节。这个值是固定的还是取决于功能的?如果它的函数依赖,那么 recur 函数只有两个声明为 'i' 和 'j' 的 int 变量,这使得 2*4= 8 个字节,那么为什么是 48 个?
标签: c static-memory-allocation