当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Is this a memory leak? How should it be done?

问题描述:

I have something like this:

void Test(void)

{

char errorMessage[256];

spintf(errorMessage,... blablabla);

throw new CustomException(errorMessage);

}

Will this be a memory leak because errorMessage will be not freed? Or will this cause an exception when accessing the message of the exception inside a try{}catch because the errorMessage has been freed when going out from the function¿?

Thanks in advance.

网友答案:

The memory of errorMessage will already be freed when accessed by the catch handler. However, you could just copy it into a std::string in CustomException's constructor.

A memory leak, on the other hand, could be caused by the exception itself, since you put it on the heap. This is not necessary.

网友答案:

The answer is yes, very probably. You should never throw objects created with new. Instead, throw values:

throw CustomException(errorMessage);

and catch using const references:

try {
  ...
}
catch( const CustomException & e ) {
  ...
}

Throwing values means that the compiler handles the lifetime of the thrown object. Also, in your code you may have another problem if the copy constructor for your exception class is not correct - this has nothing specifically to do with exception handling, however.

网友答案:

It will not cause a memory leak, but it could result in undefined behavior depending on what you are doing with that exception. I suppose memory leaks can only happen when you allocate dynamic memory

分享给朋友:
您可能感兴趣的文章:
随机阅读: