warning C4172: returning address of local variable or temporary [duplicate]

为君一笑 提交于 2019-12-06 16:44:05

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.

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

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

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

free(sMessage);

Change

    _TCHAR sReturn[MAX_PATH];

in your "GetApplicationPath" to

    static _TCHAR sReturn[MAX_PATH];

If only one thread is going to be calling GetApplicationPath(), dynamically allocating this string is overkill. Marking a local variable as static allocates space for it with the globals, so that space doesn't get stepped on when you exit from the function.

Consider modifying:

  LPTSTR GetApplicationPath ( HINSTANCE Instance )  

to something like

  void GetApplicationPath ( HINSTANCE Instance, LPTSTR str )  

This will eliminate the need to return a local variable.

The warning says it all. In the function GetApplicationPath you are returning sReturn which is local to the function. Local variables cease to exist once the function returns and reference to them after function returns is incorrect.

To overcome this you can dynamically allocate space sof sReturn as:

sReturn = malloc(sizeof(_TCHAR) * MAX_PATH);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!