C指针

今天在图书馆发现了一本C指针的书
二话没说借下回来研究

指针与内存段

首先操作实现了内存段的实验
分段内存模型主要由代码(Code)段、数据(Data)段、
未初始化(BSS)段、栈(Stack)段、堆(Heap)段等组成
还涉及到如帧(基)指针EBP、栈指针(ESP)以及指令指针EIP等概念

分段模型代码如下

#include<stdio.h>
#include<stdlib.h>
int globel_uninit;//BBS段->全局未初始化变量,运行时先初始化为0
int globel_init = 10;//数据段->全局初始化变量
void foo(void){
    static int num = 0;//栈帧计数
    int autovar;//(自动)局部变量
    int *ptr_foo = (int *)malloc(sizeof(int));
    if(++num == 4)return;//创建4个栈帧
    printf("Stack frame number %d: address of autovar: %p\n",num,&autovar);
    printf("Address of heap allocated inside foo() %p\n",ptr_foo);
    foo();
}
int main(){
    int *ptr_main = (int *)malloc(sizeof(int));
    printf("Text Segment:\n");
    printf("Address of main: %p\n",main);
    printf("Address of afunc: %p\n",foo);
    printf("Stack Locations:\n");
    foo();
    printf("Data Segment:\n");
    printf("Address of globel_init: %p\n",&globel_init);
    printf("BSS Segment:\n");
    printf("Address of globel_uninit: %p\n",&globel_uninit);
    printf("Heap Segment:\n");
    printf("Address of heap allocated inside main() %p\n",ptr_main);
    free(ptr_main);//经实验free并未对结果造成影响,但是个人认为应当加上
    return 0;

编译、输出的结果为

➜ gcc -o Memory Memory.c
➜ ./Memory
Text Segment:
Address of main: 0x100b48d50
Address of afunc: 0x100b48ce0
Stack Locations:
Stack frame number 1: address of autovar: 0x7ffeef0ba9ac
Address of heap allocated inside foo() 0x7f927c405860
Stack frame number 2: address of autovar: 0x7ffeef0ba97c
Address of heap allocated inside foo() 0x7f927c405870
Stack frame number 3: address of autovar: 0x7ffeef0ba94c
Address of heap allocated inside foo() 0x7f927c405880
Data Segment:
Address of globel_init: 0x100b4d018
BSS Segment:
Address of globel_uninit: 0x100b4d020
Heap Segment:
Address of heap allocated inside main() 0x7f927c405850

通过输出变量的地址可以看出不同变量的存储位置


未完待续

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值