我有以下代码:
#include int global_var; int global_initialized_var=5; void function(){ int stack_var; printf("The function's stack_var is at address 0x%08xn", &stack_var); } int main(){ int stack_var; static int static_initialized_var = 5; static int static_var; int *heap_var_ptr; heap_var_ptr = (int *) malloc(4); // Next variables will be at data segment printf("global_initialized_var is at address 0x%08xn", &global_initialized_var); printf("static_initialized_var is at address 0x%08xnn", &static_initialized_var); // These will be in the bss segment printf("static_var is at address 0x%08xn", &static_var); printf("global_var is at address 0x%08xn", &global_var); // This will be in heap segment printf("heap_var is at address 0x%08xnn", heap_var_ptr); // These will be in stack segment printf("stack_var is at address 0x%08xn", &stack_var); function(); }
我回过头来看:
# ./memory_segments global_initialized_var is at address 0x0804a018 static_initialized_var is at address 0x0804a01c static_var is at address 0x0804a028 global_var is at address 0x0804a02c heap_var is at address 0x09285008 stack_var is at address 0xbf809fbc The function's stack_var is at address 0xbf809f8c
假设前两个变量因为它们被初始化为static和global应该在.data段中,其中2个static_var和global_var应该在.bss段中。 我认为我得到的地址暗示它们都在同一个内存区域。 我会盲目猜测,我会说这是.bss段。
无论如何,问题是以下,我是对的? 如果我是如何找到这些区域的“限制”(bss,数据等)或从哪里开始等等。
假设您正在编译类似gcc memaddr.c -g -o memaddr
,您可以使用objdump -h
来显示您的部分的大小和地址:
$ objdump -h memaddr | grep -e'尺寸'-e' .data'-e' .bss' Idx名称大小VMA LMA文件关闭Algn 23。数据00000018 0000000000601018 0000000000601018 00001018 2 ** 3 24 .bss 00000018 0000000000601030 0000000000601030 00001030 2 ** 3 $
您还可以使用objdump -t
显示符号所属的地址和部分:
$ objdump -t memaddr | grep“_var” 000000000060102c l O .data 0000000000000004 static_initialized_var.2049 0000000000601040 l O .bss 0000000000000004 static_var.2050 0000000000601044 g O .bss 0000000000000004 global_var 0000000000601028 g O .data 0000000000000004 global_initialized_var $
所以我们可以看到.data和.bss部分相当小,碰巧彼此相邻,所以.data和.bss地址非常接近就不足为奇了。
以上就是c/c++开发分享data / bss / heap和stack中的内存分配相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/559944.html