内存泄露

C++语言 码拜 8年前 (2016-05-21) 1253次浏览
/*在字符串中找出连续最长的数字串,并把这个串的长度返回*/

 unsigned int Continumax(char** pOutputstr,  char* inputstr)
 {
	if(inputstr==NULL)
		{ **pOutputstr="\0";
	      return 0;
	}
	int i=0,j=0;
	int len=0;//每个数字串的长度
	char *p=NULL;
	char *temp=NULL;
	temp=(char*)malloc(sizeof(char)*30);
	while(inputstr[i]!="\0")
	{
		if(inputstr[i]>="0"&&inputstr[i]<="9")
		{
			p=inputstr+i;
			for(j=i;;j++)
				if(inputstr[j]<"0"||inputstr[j]>"9")
				{
					p[j-i]="\0";
					if(len<=j-i)
					{
						len=j-i;
						strcpy(temp,p);

					}
					break;
					if(inputstr[j]=="\0")
					{
						*pOutputstr=temp;
						return len;
					}
				}
			i=j;
		}
		i++;

	}
	if(len==0)
		{
			*pOutputstr=(char*)malloc(sizeof(char)*30);
			**pOutputstr="\0";
			return 0;
	     }
	*pOutputstr=(char*)malloc(sizeof(char)*30);
	*pOutputstr=temp;
	//free(temp);
	return len;
 }
int main()
{
   char input[100];
   cin.getline(input,100);
   char *out=NULL;
   int n;
   n=Continumax(&out,input);
   cout<<n<<" ";
  cout<<out<<" ";
   free(out); 
}

oJ中,有内存泄露错误,但是在调用函数里释放掉temp,结果肯定出错。问一下在现有结构中该怎么样更改呢?

解决方案

35

shared_ptr
unique_ptr

5

引用:

shared_ptr
unique_ptr

内存泄露


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明内存泄露
喜欢 (0)
[1034331897@qq.com]
分享 (0)