In getDocumentRootA()
you are retuning a pointer to a member variable of a stack allocated object which is bad since once you leave the function it will be cleaned up. It is even worse since you should not be modifying the internal member of string
so there are two problems there:
string documentRootTemp = documentRoot_T;
^^^^^^
Object on the stack
char* documentRoot = const_cast<char*>(documentRootTemp.c_str());
^^^^^^
Pointer to said object
return documentRoot;
^^^^^
Returning said pointer
and here is where you are using that pointer:
char* path = getDocumentRootA();
strcat(path, "Test//file.test");
^^^^
Modifying pointer to object that does not exist anymore
You should probably just return a std::string
from GetDocumentRootA()
and then in check
using c_str
in the places where you need const char *
. You can use the +=
operator to append char *
to a std::string
, see this reference. Here is a very basic example, to make my suggestion more concrete:
#include <string>
#include <iostream>
std::string getDocumentRootA()
{
std::string str( "Path//") ;
return str ;
}
bool doesFileExist( const char *p )
{
bool ret = false ;
// Do checking here
return ret ;
}
int main()
{
std::string str2( getDocumentRootA() ) ;
str2 += "Test//file.test" ;
std::cout << str2.c_str() << std::endl ;
if( doesFileExist( str2.c_str() ))
{
std::cout << "Yes" << std::endl ;
}
else
{
std::cout << "No" << std::endl ;
}
}