In VC++, when I typecast the const char* value returned by std::string::c_str() to char* and print the casted value, nothing gets printed on the screen. Here is the code snippet
#include "stdafx.h"
#include <string>
using namespace std;
string test() { return(string("HELLO"));}
int _tmain(int argc, _TCHAR* argv[])
{
char* val;
val = (char*) test().c_str();
printf("\n %s\n", val);
return 0;
}
When I simply check the ASCII value at val[0] it is 0. But under G++, the text HELLO gets displayed.
Is the cast from const char* to char* a non-standard one whose results are not defined?
The cast is fine as long as you don’t modify the value or read from it after altering the string (you should get at least a warning though).
The problem is that you call the function on a temporary (the temporary is the
stringreturned bycat()). After the;, the temporary goes out of scope andvalstill points to memory managed by the temp. It’s UB reading from it.