#include <stdio.h> #include <stdlib.h> #include <sys/ipc.h> #include <sys/shm.h> int g_i1; // bss段,未初始化数据段,会被自动初始化为0 int g_i2 = 100; // 初始化数据段 int func() // 正文段 { return 0; } int main(int argc, char* argv[]) { int shmid = -1; char *ptr, *shmptr; if (argc != 2) { printf("need 1 argument\n"); return -1; } ptr = (char*) malloc(100); shmid = shmget(IPC_PRIVATE, 1024 * 1024, 0666); shmptr = (char*) shmat(shmid, 0, 0); printf("%p(command line argument around)\n", &argv[1]); // 命令行参数和环境变量 printf("%p(stack around)\n", &shmid); // 栈 printf("%p(shared memory attached)\n", shmptr); printf("%p(heap around)\n", ptr); // 堆 printf("%p(bss around)\n", &g_i1); printf("%p(data segment around)\n", &g_i2); printf("%p(func around)\n", func); shmctl(shmid, IPC_RMID, 0); return 0;
}
程序执行结果:
0xbf974308(command line argument around) 0xbf974258(stack around) 0xb7e07000(shared memory attached) 0x8448008(heap around) 0x80499d0(bss around) 0x80499c4(data segment around) 0x8048564(func around)
注:以上地址从上往下逐个减小。