内存四区代码演示

本文总字数:1826,阅读预计需要:5分钟

栈区特点:

复制代码
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *pMem1()
{
    char *p1 = "hellow12345";
    return p1;
}
//函数调用完毕后,函数内部的栈区变量就会被销毁

char *pMem2()
{
    char *p2 = "hellow12345";
    return p2;
}

int main(void)
{
    char *p1 = NULL;
    char *p2 = NULL;
    p1 = pMem1();
    p2 = pMem2();
    printf("p1 = %s, p1 = %p\n", p1, p1);
    printf("p2 = %s, p2 = %p\n", p2, p2);
    return 0;
}

/*
输出结果:
p1 = hellow12345, p1 = 00C57BAC
p2 = hellow12345, p2 = 00C57BAC
*/
复制代码

内存四区情况:

 

复制代码
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *p_str()
{
    char str[100] = "hehe";
    return str;
}


int main(void)
{
    char *p = NULL;

    p = p_str();

    printf("p = %s, p = %p\n", p, p);

    return 0;

}

/*
输出结果:
p = 烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫烫
烫烫烫烫烫烫烫烫烫烫烫烫烫烫D?, p = 0020F5D8
*/
复制代码

堆区特点: 

复制代码
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *phead()
{
    char *tmp = (char *)malloc(100);
    if (tmp == NULL)
    {
        return NULL;
    }
    strcpy(tmp, "hehe");
    return tmp;
}


int main(void)
{
    char *p = NULL;

    p = phead();

    printf("p = %s, p = %p\n", p, p);

    return 0;

}

/*
输出结果:
p = hehe, p = 01135028
*/
复制代码

 

说明程序的运行过程(内存四区)

以下面代码说明

复制代码
#define  _CRT_SECURE_NO_WARNINGS 
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *pMem1()
{
    char *p1 = "hellow12345";
    return p1;
}
//函数调用完毕后,函数内部的栈区变量就会被销毁

char *pMem2()
{
    char *p2 = "hellow12345";
    return p2;
}

int main(void)
{
    char *p1 = NULL;
    char *p2 = NULL;
    p1 = pMem1();
    p2 = pMem2();
    printf("p1 = %s, p1 = %p\n", p1, p1);
    printf("p2 = %s, p2 = %p\n", p2, p2);
    return 0;
}
复制代码

 栈区先入后出指的是内存销毁过程,栈区的变量可以随时访问(就像局部变量可以在函数体内随时使用),但是销毁时是一定执行先进后出的原则的

posted @   北极星!  阅读(64)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
>>博客统计:随笔 -615  文章 -0  评论 -50 
点击右上角即可分享
微信分享提示