82.C语言中的内存布局2
目录
一.实验代码
二.视频教程
一.实验代码
#include <stdio.h>
#include <stdlib.h>char *test_str = "hello world"; //.data
int test_a = 1; //.data
int test_b = 0; //.bss
int test_c; //.bss
static int test_d = 1; //.data
static int test_e = 0; //.bss
static int test_f; //.bss
const int test_g = 1; //.rodataint main(void)
{static int test_h = 3; //.datastatic int test_i = 0; //.bssstatic int test_j; //.bssint test_k;//stackchar *test_str1 = malloc(10); //heapprintf("test_k addr is %p\n",&test_k); printf("malloc addr is %p\n",test_str1); printf("test_str1 addr is %p\n",&test_str1); while(1);return 0;}
编译程序,然后使用命令nm test | grep test_查看内存分布
符号B,D等含义如下:
B/b:.bss段
D/d:.data段
R/r:.rodata段
T/t:.text段
需要注意的是,char *test_str = "hello world"; 中的test_str在.data段,而字符串hello world在.rodata段。
查看.rodata段中的内容:
堆栈如何查看?
先使用命令ps -al查看test的pid号,pid号为8242,然后使用命令cat /proc/8242/maps查看内存布局。如下图:
会发现 int test_k变量地址位于栈。char *test_str1指针变量地址位于栈,而char *test_str1指针变量中存放的地址(由malloc函数申请的地址)位于堆。
二.视频教程
82.C语言中的内存分布2_哔哩哔哩_bilibili