内存分配以及指针处理的相关测试代码

来源:互联网 发布:java错误等级 编辑:程序博客网 时间:2024/06/06 11:37
#include<stdio.h>#include<stdlib.h>#include<assert.h>void GetStr(char *p){p="123456";//指向一个全局数据区  字符串常量int a=10;//栈区static int b=10;//全局静态区char *q=(char*)malloc(12);//堆区char *r=(char*)malloc(12);//堆区printf("addr p=%p  a=%p  b=%p q=%p r=%p\n",p,&a,&b,q,r);//全局数据区{p,b}  栈区{a}  堆区{q,r}free(q);//释放指针内存空间free(r);q=NULL;//防止野指针r=NULL;}char *GetStr2(void){//数组char p[]="123456";//栈内存数据return p;//这里强调不要用 return 语句返回指向“栈内存”的指针,因为该内存在函数结束时自动消亡  结果这里出现警告!}void test(){char *p=NULL;p=(char*)malloc(12);GetStr(p);printf("======\n\np=%p\n",p);//堆区p=GetStr2();//出错!!//printf("%s\n",p);assert(p!=NULL);printf("%s\n",p);free(p);p=NULL;}char *GetStr3(){char *p="123456";return p;}void test2(void){char *str =NULL;printf("addr str=%p\n",str);//str地址之后发生了变化str = GetStr3();printf("addr str=%p\n",str);printf("%s\n",str) ;//GetStr3 设计无效 随时调用都可以/*GetStr3 内的“123456”是常量字符串,位于静态存储区,它在程序生命期内 *恒定不变。无论什么时候调用 GetString2,它返回的始终是同一个“只读”的内存块。 */}int main(){//test();test2();return 0;}

0 0