直接传递字符串作为参数是否会导致c++内存泄漏

Can directly passing strings as parameter cause Memory leak in C++?

本文关键字:c++ 泄漏 内存 是否 参数 字符串      更新时间:2023-10-16

在我的MFC应用程序中,当我在Visual Studio中从调试模式关闭它时,输出窗口有这样的行-

f:ddvctoolsvc7libsshipatlmfcsrcmfcstrcore.cpp(156) : {415} normal block at 0x028BC410, 21 bytes long. Data: <T  x            > 54 CD FB 78 04 00 00 00 04 00 00 00 01 00 00 00 "

当我使用分配号创建断点时,它指向代码:

if (CMFCToolBar::GetUserImages() == NULL)
{
    if (m_UserImages.Load(_T(".\UserImages.bmp"))) //call-stack points to this line.
    {
        CMFCToolBar::SetUserImages(&m_UserImages);
    }
}

另一个示例如下:

CMainFrame::CMainFrame()
{
theApp.m_nAppLook = theApp.GetInt(_T("ApplicationLook"), ID_VIEW_APPLOOK_VS_2008);//call-stack points to this line.
}

我发现所有其他分配编号都导致字符串直接作为参数传递给函数的行。我的问题是:这真的是内存泄漏吗?如果是,那么如何避免这种情况;也许初始化一个CString变量并将其作为该函数的参数传递?

回答你的标题-字符串文字不需要被释放。

至于传递给函数——这取决于函数用它做什么。

例如,不管你传递给它什么,这个函数都会产生内存泄漏:

void foo(const char* s) {
    strdup(s); // Memory leak!
}
foo("abc"); // There's a memory leak because foo just created a copy using strdup which it didn't free!