C++ 初始化 const char * 没有任何内存泄漏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14766864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:40:32  来源:igfitidea点击:

Initialize const char * with out any memory leaks

c++stringcharconst

提问by Jabez

Below is my sample code. Its just a sample which is similar to the code which i'm using in my applicaiton.

下面是我的示例代码。它只是一个示例,类似于我在我的应用程序中使用的代码。

#define STR_SIZE 32

void someThirdPartyFunc(const char* someStr);

void getString(int Num, const char* myStr)
{
  char tempStr[] = "MyTempString=";
  int size = strlen(tempStr) + 2;
  snprintf((char*)myStr, size, "%s%d", tempStr, Num);
}

int main()
{
  const char * myStr = new char(STR_SIZE);
  getString(1, myStr); // get the formated string by sending the number
  someThirdPartyFunc(myStr); // send the string to the thirdpartyFunction
  delete myStr;

  return 0;
}

I am getting an exception if i use this code. I think the problem is with deleting the "myStr". But delete is really necessary.

如果我使用此代码,则会出现异常。我认为问题在于删除“myStr”。但是删除真的很有必要。

Is there any other way to format the string in getString and send it to the ThirdPartyFunc??

有没有其他方法可以格式化 getString 中的字符串并将其发送到 ThirdPartyFunc?

Thanks in advance.

提前致谢。

回答by akira

you are allocating not an array of chars but one char with this line:

您分配的不是一个字符数组,而是一个字符与这一行:

 const char * myStr = new char(STR_SIZE);

and that one allocated char is initialized with the value of STR_SIZE, causing a "char overflow" in this case.

并且一个分配的字符被初始化为 的值STR_SIZE,在这种情况下会导致“字符溢出”。

if you want an array of size STR_SIZE:

如果你想要一个大小的数组STR_SIZE

 const char * myStr = new char[STR_SIZE];

(note the rectangular [ ]). you have to deallocate such allocated chunk of memory by using the delete[]operator.

(注意矩形 [ ])。您必须使用delete[]运算符来释放这样分配的内存块。

personal note: the code you have written above (manually allocated strings etc) is good educational wise; you will do a lot of such mistakes and thus learn about the inner workings of C / C++. for production code you do not want that, for production code you want std::stringor other string-containers to avoid repeating string-related mistakes. in general you are not the one who sucessfully reinvent how string-libraries will work. the same is true for other container-types like dynamically-growable-arrays (std::vector) or dictionary-types or whatever. but for educational fiddling around your code above serves a good purpose.

个人说明:您在上面编写的代码(手动分配的字符串等)具有很好的教育意义;你会犯很多这样的错误,从而了解 C/C++ 的内部工作原理。对于您不想要的生产代码,对于您想要的生产代码std::string或其他字符串容器,以避免重复与字符串相关的错误。一般来说,你不是成功地重新发明字符串库如何工作的人。对于其他容器类型(例如动态可增长数组 ( std::vector) 或字典类型或其他类型)也是如此。但是为了教育性地摆弄上面的代码,这是一个很好的目的。

there are other problems in your code snippet (handing over const char*to a function and then modifying the ram, not calculating correctly the sizeparameter when calling snprintfetc), but these are not related to your segfault-problem.

您的代码片段中还有其他问题(移交const char*给函数然后修改 ram,size在调用时没有正确计算参数snprintf等),但这些与您的段错误问题无关。

回答by Cheers and hth. - Alf

Re the technical, instead of

重新技术,而不是

const char * myStr = new char(STR_SIZE);

do

char const myStr[STR_SIZE] = "";

Note that both have the problem that the string can’t be modified.

请注意,两者都有无法修改字符串的问题。

But you only asked about the allocation/deallocation problem.

但是您只询问了分配/解除分配问题。



But then, there's so much wrong at levels above the language-technical.

但是,在语言技术以上的级别上有很多错误。

Here's the original code, complete:

这是原始代码,完整:

void someThirdPartyFunc(const char* someStr);

void getString(int Num, const char* myStr)
{
  char tempStr[] = "MyTempString=";
  int size = strlen(tempStr) + 2;
  snprintf((char*)myStr, size, "%s%d", tempStr, Num);
}

int main()
{
  const char * myStr = new char(STR_SIZE);
  getString(1, myStr); // get the formated string by sending the number
  someThirdPartyFunc(myStr); // send the string to the thirdpartyFunction
  delete myStr;

  return 0;
}

Here's how to do that at the C++ level:

以下是在 C++ 级别执行此操作的方法:

#include <string>           // std::string
#include <sstream>          // std::ostringstream
using namespace std;

void someThirdPartyFunc( char const* ) {}

string getString( int const num )
{
    ostringstream stream;
    stream  << "MyTempString=" << num;
    return stream.str();
}

int main()
{
  someThirdPartyFunc( getString( 1 ).c_str() );
}

The #definedisappeared out of the more natural code, but note that it can very easily lead to undesired text substitutions, even with all uppercase macro names. And shouting all uppercase is an eyesore anyway (which is why it's the macro name convention, as opposed to some other convention). In C++ simply use constinstead.

#define更自然的代码消失了,但要注意,它可以很容易导致不想要的文本替换,即使全部使用大写宏名。无论如何,大写都是大写的(这就是为什么它是宏名称约定,而不是其他约定)。在 C++ 中,只需使用即可const