开发者

Is this a memory leak? How should it be done?

开发者 https://www.devze.com 2022-12-17 18:54 出处:网络
I have something like this: void Test(void) { char errorMessage[256]; spintf(errorMessage,... blablabla);

I have something like this:

void Test(void)
{
    char errorMessage[256];

    spintf(errorMessage,... blablabla);
    throw new CustomException(errorMessage);
}

Will this be a m开发者_高级运维emory 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号