您的位置:首页 > 其它

2008 July 16th Wenesday (七月 十六日 水曜日)

2008-08-01 20:39 344 查看
   There is a memory leak example.

void test2(int n)
{
    double * ar = new double
;
    ...
    if (oh_no)
        throw exception();
    ...
    delete [] ar;
    return;
}

  Unwinding the stack removes the variable ar from the stack. But the premature termination of the function
means the delete [] statement at the end of the function is skipped. The pointer is gone, but the memory block
it pointed to is still intact and inaccessible. In short, there is a memory leak.

  The leak can be avoided.

void test3(int n)
{
    double * ar = new double
;
    ...
    try {
        if (oh_no)
            throw exception();
    }
    catch(exception & ex)
    {
        delete [] ar;
        throw;
    }
    ...
    delete [] ar;
    return;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息