返回类型为指针的函数里面动态分配的指针怎么释放

hertcloud 2005-11-28 01:42:43
// testpoint.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;
char* test()
{
char* mmm = (char*)malloc(100);
mmm = "sflajdfsda";

return mmm;
//mmm怎么free呢?
}



int _tmain(int argc, _TCHAR* argv[])
{
char* tt = test(); //这里的tt需要free吗?

cout << *tt << endl; //这里只输出了s 怎么输出全部字符串呢?
cin.get();
//free(tt);
//free(mmm); 
return 0;
}
...全文
249 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
fz97532 2005-11-28
  • 打赏
  • 举报
回复
http://www.fm201.com/framework-1.htm
看看这个
上有
BeRoy 2005-11-28
  • 打赏
  • 举报
回复
int _tmain(int argc, _TCHAR* argv[])
{
char* tt = test(); //要free

cout << tt << endl;
cin.get();
free(tt);
//free(mmm); 
return 0;
}
lzp229 2005-11-28
  • 打赏
  • 举报
回复
char* test()
{
int i;
char *t;
char* mmm = (char*)malloc(100);
t = mmm;
for(i=0;i<5;i++)
{
*t = 't';
t++;
}
return mmm;
}
int main()
{
int i;
char* tt = test(); //?里的tt需要free??
for(i=0;i<5;i++)
{
printf("%c",*tt);
}
free(tt);
return 0;
}
这样可以
sasdaa 2005-11-28
  • 打赏
  • 举报
回复
内存泄漏.分配的内存将无法释放,他指向得静态存储区,建议看看高质量C++编程指南
csucdl 2005-11-28
  • 打赏
  • 举报
回复
wohow() 说得对
这样啊
strcpy(mmm, "sflajdfsda");
snowbirdfly 2005-11-28
  • 打赏
  • 举报
回复
#include <malloc.h>
#include <iostream>
using namespace std;
char* test()
{
char *mmm = (char*)malloc(100);
mmm = "sflajdfsda";

return mmm;
//mmm怎么free呢?
}



int main()
{
char* tt = test(); //这里的tt需要free吗?

cout << tt << endl; //这里只输出了s 怎么输出全部字符串呢?
cin.get();
return 0;
}
iShan 2005-11-28
  • 打赏
  • 举报
回复
你可以使用strcpy(),或者实用strcat()这些标准库函数给它赋值。
hertcloud 2005-11-28
  • 打赏
  • 举报
回复
那我应该 怎么写 才对呢?
wohow 2005-11-28
  • 打赏
  • 举报
回复
char* mmm = (char*)malloc(100);
mmm = "sflajdfsda";
严重的错误代码。分配的内存将无法释放。
lzp229 2005-11-28
  • 打赏
  • 举报
回复
cout << *tt << endl; //这里只输出了s 怎么输出全部字符串呢?
printf("%s",tt);
c语言里面这么做就是输出字符串

64,677

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧