为什么这个函数会产生内存泄漏?
CString FormatText(unsigned long value,int len,int point)
{
CString caption,stredtctrlall;
int captionlen,i;
caption.Format(_T("%d"),value);
captionlen=caption.GetLength();
if(caption.GetLength()<len)
{
for(i=len;i>captionlen;i--)
caption="0"+caption;
}
else if(caption.GetLength()>len)
{
caption=caption.Left(len);
}
if(point>0) //在字符串中插入小数点
{
CString stredtctrl, tempedtctrl_left, tempedtctrl_right;
stredtctrl=caption;
tempedtctrl_left=stredtctrl.Left (stredtctrl.GetLength()-point);
tempedtctrl_right=stredtctrl.Right(point); stredtctrlall=tempedtctrl_left+"."+tempedtctrl_right;
}
else
stredtctrlall=caption ;
return stredtctrlall;
}
那什么书上或MS的例子一般都用数组来实现字符串呢?
char * str="你好";//没有用malloc或new给它分配分间
//然后又在程式的多处给它重新付不同的值
str="hello world"
//这样会产生内存泄漏吗?
不会出现内存泄漏,其实
char * str="你好";
相当于你声明了一个匿名的字符串,假设为x1;
你的第一行代码相当于:
char x1[]="你好";
char * str=x1;
后面一行也一样相当于:
char x2[]="hello world";
str=x2;
只要不采用动态内存分配,就不存在内存泄漏的问题。
只有采用了动态内存分配才有可能出现内存泄漏