温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

关于malloc内存申请的深入研究

发布时间:2020-07-22 16:38:08 来源:网络 阅读:704 作者:313119992 栏目:开发技术

在内存申请和使用上总是会出现一些莫名其妙的问题,今天刚好又碰到了,这里总结一下。

//1.编译可以通过,但是执行不过。卡死在注释那一句
void test()
{
	char * str = (char *)malloc(100);
	strcpy(str,"hello");
	free(str);
	if(str != NULL)
	{
		strcpy(str,"world");
		printf("%s\n",str);//因为str已经free,所以对str的访问出现问题,卡死在这一步
	}
}
//---------------------------------------
//2.双指针是OK的
void getMemory(char **p,int num)
{
	*p = (char *)malloc(num);
}

void test()
{
	char *str = NULL;
	getMemory(&str,100);
	strcpy(str,"hello");
	printf("%s\n",str);
}

//-----------------------------------------
//3.编译通过,执行通过,返回垃圾文字。
char * getmemory()
{
	char p[] = "hello world";
	return p;
}

void test()
{
	char *str = NULL;
	str = getmemory();
	printf("%s\n", str);//因为getmemory()中返回的是局部变量的地址,
	//所以在getmemory()执行完毕后,该变量自动释放。所以访问失败。输出一些垃圾文字。
}
//-----------------------------------------
//4.编译通过,执行失败。
void getmemory(char *p)
{
	p = (char *)malloc(100);//内存空间申请后,指向这一空间的指针被释放
}

void test()
{
	char *str = NULL;
	getmemory(str);
	strcpy(str, "hello world");//str没有空间来容纳后面的字符串
	printf("%s\n", str);
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI