您的位置:首页 > 其它

内存四区的笔记

2016-05-27 18:36 232 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//静态存储区域的理解
char *getStr1(){
char *p1 = "abcdef";
return p1;
}

char *getStr2(){
char *p2 = "abcdef";
return p2;
}

//以上两个值如果都相等的话,那么他们公用一个内存空间
//结论:指针指向谁,就把谁的地址赋值给指针
void main(){
char *p1 = NULL;
char *p2 = NULL;
p1 = getStr1();
p2 = getStr2();
//打印p1,p2所指向内存空间的数据

printf("p1:%s,p2:%s\n",p1,p2);
//打印p1,p2的值
printf("p1:%d,p2:%d\n",p1,p2);
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//堆
char *getMem(int num){
char *p1 = NULL;
p1 = (char *)malloc(sizeof(char) * num);//p1申请空间 ,永久存在,除非操作系统回收
if(p1 == NULL){
return NULL;
}
return p1;//这里已经地址已经指向分配的堆空间
}
//栈
//注意:return不是把内存块的64个字节给return,出来,而是把内存块的首地址传给tmp
//理解指针的关键,是在内存,没有内存哪来的指针
char *getMen2(){
char buf[64]; //临时变量
strcpy(buf,"123456789");
//printf("buf:%s\n",buf);
return buf;//传地址的时候栈区自动析构掉,所以传过来没用
}

void main(){
char *tmp = NULL;
tmp = getMem(10);
if(tmp == NULL){
return;
}
strcpy(tmp,"111222");

tmp = getMen2();
printf("tmp:%s\n",tmp);
system("pause");
}

堆栈的属性测试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(){
int a;
int b;
char buf[128];//静态编译的时候 buf所代表的内存空间的标号 就已经定义下来了。
//不管栈开口向上还是向下,buf的内存buf+1永远都是向上的。
//栈的生长方向和buff的生长方向不是一回事
printf("&a:%d,&b:%d\n",&a,&b);
//结论得出:B的内存地址比A小,那么证明栈的开口是向下的
/*   |----\
*	|   A  \
*	|    B   \
*  |    buff  \
<-首地址
*  |			\
*/
//但是也不一定,一般都是开口向下的
system("pause");
//C++的编译器只会为每个程序建立一个内存四区
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: