It's ok to have a function with a char*
return type, like that :
char* f() {
char* r = new char[20];
//Your logic
return r;
}
int main() {
char* v = f();
//More logic
//Don't forget to delete the dynamically allocated data when you don't need it
delete[] v;
}
However, your code has a problem : you try to return the local variable ownPth
, and that's a problem.
In the line :
return ownPth;
you just return the pointer to the first element of the char array, which will be "destroyed" after the function call, and trying to dereference the returned value from outside will result in undefined behavior.
What you should do is using std::string
like that :
std::string GetModulePath()
{
char ownPth[MAX_PATH] = {0}; // Zero initialization
HMODULE hModule = GetModuleHandle(NULL);
if (hModule != NULL)
{
GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
}
return std::string(ownPth);
}
Or, if you really want to use char arrays, you should use heap allocation ( with new
and delete
), but i don't recommand it :
char* GetModulePath()
{
char* ownPth = new char[MAX_PATH];
memset(ownPth,0,MAX_PATH); //Write zeroes in the allocated memory
HMODULE hModule = GetModuleHandle(NULL);
if (hModule != NULL)
{
GetModuleFileName(hModule, ownPth, MAX_PATH);
//Not using sizeof, because now, ownPth is not a char array, it's a pointer
}
return ownPth; // You will need to delete[] it after, else it's a memory leak
}
As said in the comments below, it's very poor practice, and chances are, at some point, you will forget to call delete[]
just after using it, after a function call, creating a memory leak