malloc 不能返回动态内存

<span style="font-family:Courier New;font-size:14px;">#include <stdio.h>
#include <stdlib.h>
void getmemory(char *p)
{
	p=(char *) malloc(100);
	strcpy(p,"hello world");
}
int main( )
{
	char *str=NULL;
	getmemory(str);//等于getmemory(char *p=str);你函数里p倒是获取了内存,但是str什么都没有,要传引用,明白不
	printf("%s/n",str);
	free(str);
	return 0;
}</span>

P不是有100个字符了吗 ? getmemory中的malloc 不能返回动态内存 这个解释不太懂

注意传值与传地址区别
尤其当参数是指针时 容易忽略,请不要用值传递(这样会导致str没有指向分配到的内存),C里没有引用的话就用指针传。
程序崩溃,getmemory中的malloc 不能返回动态内存, free()对str操作很危险
strcpy(p,"hello world");

C语言是值传递,故在函数调用中修改的值,并不会返传至主调函数。所以原程序在getmemory函数中malloc获得的地址空间的首地址的值只在函数内部有效,函数调用结束后该值就丢失了

对比:

#include <stdio.h> 
#include <stdlib.h> 
void getmemory(char **p) 
{ 
	*p=(char *) malloc(100); 
	strcpy(*p,"hello world"); 
} 
int main( ) 
{ 
	char *str=NULL; 
	getmemory(&str); 
	printf("%s/n",str); 
	free(str); 
	return 0; 
} 


void getmemory(char &*p)
{
p=(char *) malloc(100); 
strcpy(p,"hello world");
} 
//或者
void getmemory(char **p) 
{ 
*p=(char *)malloc(100); 
strcpy(*p,"hello world"); 
}

你那样做开始str和p指向的一样是NULL(即内容一样),但是p=(char *) malloc(100); 后str仍然是NULL,但str得到了新的内存~

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值