C语言之简析malloc与栈
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *getstr()
{
char *p = NULL;
p = (char *)malloc(sizeof(char));
printf("alloc %p\n", p);
return p;
}
void freestr(char *p)
{
printf("free %p\n", p);
free(p);
}
int main()
{
char *p = NULL;
int cmd;
while(1)
{
scanf("%d", &cmd);
if(cmd == 1)
p = getstr();
else if(cmd == 0)
freestr(p);
else
{
p = (char*)malloc(sizeof(char));
printf("get %p\n", p);
}
}
}
1
alloc 0x1e64420
1
alloc 0x1e64850
1
alloc 0x1e64870
1
alloc 0x1e64890
0
free 0x1e64890
//地址越来越大,说明malloc是向上延伸的
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void fun(int i)
{
int num = 1;
printf("%p\n", &num);
if(i <= 0)
return;
else
fun(i-1);
}
int main()
{
fun(4);
}
/*输出
0x7ffffed15e04
0x7ffffed15dd4
0x7ffffed15da4
0x7ffffed15d74
0x7ffffed15d44
*/地址下降,函数是在栈中调用,说明栈的地址空间是向下减小的