警告C4172:返回局部变量或临时地址 [英] warning C4172: returning address of local variable or temporary

查看:692
本文介绍了警告C4172:返回局部变量或临时地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

指向局部变量的指针

我读过很多其他文章该网站上关于相同问题的主题,知道这很常见。但是我想我很傻,无法找出正确的方法来做。因此,我对其中的另一个问题表示歉意,希望有人能给我一个简单的解决方案和/或解释。

I've read a lot of other topics on this site about the same problem knowing it would be common. But I guess I'm dumb and can't figure out the proper way to do it. So, I apologize for yet another one of these questions and I'm hoping someone can give me a simple solution and/or explanation.

这里是完整的代码:

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;
}


推荐答案

现在,您是返回一个自动(堆栈)数组的地址。 总是是错误的,因为一旦函数结束,该内存的生命周期也会随之结束。

Right now, you're returning the address of an automatic (stack) array. This is always wrong, because as soon as the function ends, so does that memory's lifetime.

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

You need to use malloc (and free), or other dynamic allocation. E.g.:

_TCHAR *sReturn = malloc(sizeof(_TCHAR) * MAX_PATH);

我省略了错误检查。然后,调用代码应释放它。在 _tWinMain 中的 MessageBox 之后:

I've omitted error checking. Then later, the calling code should free it. After the MessageBox in _tWinMain:

free(sMessage);

这篇关于警告C4172:返回局部变量或临时地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆