警告C4172:返回局部变量的地址或临时变量

gui*_*ar- 1 c compiler-warnings

可能重复:
指向局部变量的指针

我已经在这个网站上阅读了很多关于同样问题的其他主题,因为我知道它很常见.但我想我是愚蠢的,无法弄清楚这样做的正确方法.所以,我为这些问题中的另一个道歉,我希望有人可以给我一个简单的解决方案和/或解释.

这是整个代码:

MAIN.C

#define WIN32_LEAN_AND_MEAN

#include <Windows.h>
#include <stdlib.h>
#include <tchar.h>


LPTSTR GetApplicationPath ( HINSTANCE Instance );


int APIENTRY _tWinMain ( HINSTANCE Instance, HINSTANCE PreviousInstance, LPTSTR CommandLine, int Show )
{
    LPTSTR sMessage = GetApplicationPath ( Instance );

    MessageBox (
        NULL,
        sMessage,
        _T ( "Caption!" ),
        MB_OK
    );

    return 0;
}


LPTSTR GetApplicationPath ( HINSTANCE Instance )
{
    _TCHAR sReturn[MAX_PATH];

    GetModuleFileName ( (HMODULE) Instance, sReturn, MAX_PATH );

    return sReturn;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 8

现在,您将返回自动(堆栈)数组的地址.这总是错误的,因为一旦函数结束,那么该内存的生命周期也是如此.

您需要使用malloc(和free)或其他动态分配.例如:

_TCHAR *sReturn = malloc(sizeof(_TCHAR) * MAX_PATH);
Run Code Online (Sandbox Code Playgroud)

我省略了错误检查.然后,调用代码应该释放它.后MessageBox_tWinMain:

free(sMessage);
Run Code Online (Sandbox Code Playgroud)