Frank Palmasani
Frank Palmasani

Reputation: 185

Why does passing a std::string to CString.Format() only crash sometimes?

Using CString.Format(), I'm passing it a std::map that returns a std::string when given an int.

So:

CString cStr;
cStr.Format("%s", IntToStdStringMap[1]);

where IntToStdStringMap[1] returns some string, we'll say "Hello, World!". The issue is that this doesn't seem to crash every time. Eventually, I'll receive an access violation.

Why might this be?

Keep in mind, that changing the code to the following:

CString cStr;
cStr.Format("%s", IntToStdStringMap[1].c_str());

alleviates the issue.

Any ideas?

Upvotes: 1

Views: 1057

Answers (1)

R Sahu
R Sahu

Reputation: 206557

Passing a std::string to CString::Format is not right. From https://msdn.microsoft.com/en-us/library/aa314327(v=vs.60).aspx:

The format has the same form and function as the format argument for the printf function.

That means, when the format specifier is %s, the expected argument type is char const*, not std::string.

Hence, use of

cStr.Format("%s", IntToStdStringMap[1]);

is cause for undefined behavior while the behavior of

cStr.Format("%s", IntToStdStringMap[1].c_str());

is well defined.

Upvotes: 5

Related Questions