内存四区代码演示
栈区特点:
#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;
}
栈区先入后出指的是内存销毁过程,栈区的变量可以随时访问(就像局部变量可以在函数体内随时使用),但是销毁时是一定执行先进后出的原则的
我们向往远方,却忽略了此刻的美丽