通过函数动态分配内存的问题
void getbuf(char *p,int num)
{
p=(char*)malloc(sizeof(char)*num);
}
int main()
{
char *pstr=NULL;
getbuf(pstr,10);
strcat(pstr, "hello ");
return 0;
}
上面这块代码有问题吗
[解决办法]
内存泄漏了
[解决办法]
很多问题.
void getbuf(char **p,int num)
{
*p=(char*)malloc(sizeof(char)*num);
}
int main()
{
char *pstr=NULL;
getbuf(&pstr,10);
strcat(pstr, "hello ");
cout < <pstr < <endl;
free(pstr);
return 0;
}
1. 冒似分到了内存, 其实内存直接泄露了. pstr 并没有获得内存.
2. 用完了要 free
[解决办法]
感谢上面的回答,如何改我知道,但是为什么那样就没有分配成功
[解决办法]
to:jixingzhong(瞌睡虫·星辰) ( ) 信誉:102 Blog
==============================
为什么不用void getbuf(char *p,int num)而用void getbuf(char **p,int num)?
点一下就行了,我们基本上没有 C C++高效编程 这本书