内存和指针(测试题2014)

#include<iostream>
using namespace std;
//
1. test 直接修改指针的值,无法成功,改进后可以
/*void getMemory(char*p)
{
	p=(char*)malloc(100);
}*/
char* getMemory(char*p)
{
	p=(char*)malloc(100);//堆
	return p;
}
void test()
{
	char*str=0;
	str=getMemory(str);
	strcpy(str,"hello world");
	printf(str);
}
//
2. test 内存在栈里,返回后空间被释放,无法成功
char *GetMemory2(void)
{
	char p[]="hello world";//栈
	return p;
}

void test2()
{
	char*str=0;
	str=GetMemory2();
	printf(str);
}

//
3. test 通过指针传递指针的值,且申请空间位于堆中,可以成功
void getMemory3(char**p,int num)
{
	*p=(char*)malloc(num);
}
void test3(void)
{
	char* str=0;
	getMemory3(&str,100);
	strcpy(str,"hello");
	printf(str);
}
//
4. test 已经free掉的内存,再次访问,可以访问,但是存在不安全因素。
void test4(void)
{
	char*str=(char*)malloc(100);
	strcpy(str,"hello4");
	free(str);
	if(str!=0)
	{
		printf("\n");
		//printf(str);
		strcpy(str,"world");
		printf(str);
	}

}


int main()
{
	
	test();
	test2();
	test3();//可以
	test4();//free后的指针,指向未分配内存,里面值是随机的,故可能不为0,

	char pp[]="helloworld!";//有分配内存,存储"hellowolrd!"可通过数组改变其值
	pp[2]='A';
	cout<<pp<<endl;
	char *ppp="helloworld";//“helloworld”是字符常量,p只是指向该内存区域,不能通过指针改变其值
	ppp[2]='A';
	cout<<*ppp<<endl;
}



//

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值