I have the following function (shortened for brevity) : (PortNo = 12345)
void startparser(){
std::ostringstream convert;
convert.str("");
convert << '"' << "c:\\some\\file path\\a_program.exe" << '"' << " " << PortNo;
std::cout << "DEBUG2 " << convert.str() <<std::endl;
char *cmd = const_cast<char*> ( convert.str().c_str() );
std::cout << "DEBUG3 " << cmd <<std::endl;
}
I compile on w10 64bit with eclipse MinGW64 and the code outputs
DEBUG2 "c:\\some\\file path\\a_program.exe" 12345
DEBUG3 "c:\\some\\file path\\a_program.exe" 12345
Now if I copy the binary and the 3 dll's it uses to a win7 64 machine and run the same code I get
DEBUG2 "c:\\some\\file path\\a_program.exe" 12345
DEBUG3 .
I don't get it? I need cmd to be an LPTSTR . Can someone please clarify? Another method to get my LPTSTR is fine too.
You're using a temp object: ostringstream::str()
returns an object which is destroyed immediately. Therefore after this line
char *cmd = const_cast<char*> ( convert.str().c_str() );
the cmd
points to memory which was used for a temp object and is therefore no longer valid.
If you really need to operate with const char*
then you need to create an intermediate string tmp = convert.str()
. Then the pointer to tmp.c_str()
will be valid within the whole scope of tmp
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.