如何通过返回const char来避免内存泄漏*

时间:2016-04-23 11:50:40

标签: c++ memory-leaks

我有一个在我的代码中使用了一百万次的函数,其中有一个内存泄漏。

输入const wchar_t*并返回const char*。 现在我明白这个指针返回(const char*)需要从调用函数中获取显式delete[](但我买不起),因为这意味着我需要在所有位置更改它。

代码如下:

inline const char * W2N(const wchar_t* wstr)
{
  int cw=lstrlenW(wstr);

  if (cw==0) 
  {
      CHAR *psz=new CHAR[1]; *psz='\0'; return psz;
  }

  int cc=WideCharToMultiByte(CP_ACP,0,wstr,cw,NULL,0,NULL,NULL);
  if (cc==0) return NULL;

  CHAR *psz=new CHAR[cc+1];
  cc=WideCharToMultiByte(CP_ACP,0,wstr,cw,psz,cc,NULL,NULL);
  if (cc==0) 
  {
      delete[] psz; return NULL;
  }

  psz[cc]='\0';
  return psz;
}

我可以围绕此功能做些什么来避免内存泄漏。

1 个答案:

答案 0 :(得分:2)

您可以,并且应该将指针包裹在std::unique_ptr<char[]>内。这将以惯用的C ++方式解决您的确切问题。

这会改变你的功能:

std::make_unique

当然,这假设您可以访问符合C ++ 14的编译器(对于std::unique_ptr),或至少符合C ++ 11(对于std::string)。

当然,正如评论中所述,您可以返回nullptr。如果您这样做,请注意从函数返回NULLheight: 100%;可能会出现段错误。