使用下面代码来分析
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int x = 1;
int y = 2;
int z = 3;
char str2[] = "hello,world";
int *a = (int *) malloc(sizeof(int));
char *str = "hello,world";
printf("%p %p %p %p %p %p\n", &x, &y, &z, str2, &a, &str);
printf("%p %p\n", a, str);
printf("hello,world\n");
return 0;
}
GDB在printf(“hello,world\n”)行下断
我们可以看出x,y,z,str2, a, str变量使用了栈内存,上图第一行就是他们的地址。其中x,y,z占4个字节(int),a和str占8个字节(指针),而str2占用了16个字节(字符串长度本身12个字节,但是有内存对齐)
查看0x7fffffffde50开始的内存块,可以得到这些地址保存的地址
可以看到0x7fffffffde50保存的内容是str的地址,因为是一个指针,所以这里是0x400710,0x7fffffffde58保存的内容是a的地址,这里是0x602010。0x7fffffffde60保存的就是str2字符串的内容,也就是说str2分配在栈,剩余的3个内存地址就是保存了x,y,z的内容。
我们可以得到malloc和字符串方式的声明使用的是堆内存,而数组方式声明字符串是使用栈内存,任何变量都会需要栈内存来保存内容。
评论
暂无评论~~