Possible Duplicate:
Pointer to local variable
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.
Here’s the entire code:
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.
You need to use malloc (and free), or other dynamic allocation. E.g.:
I’ve omitted error checking. Then later, the calling code should free it. After the
MessageBoxin_tWinMain: