Tuntable
Tuntable

Reputation: 3574

C++ Operator+ string long produces Segmentation Fault

The following code produces a segmentation fault with only the xxx line printed (ie before the "pre concat").

cerr << "xxx + " << ((long long) timev);
string cname = "MyKey" + ((long long) timev);

string operator+(const string& str, long long nr) {
  cerr << "Pre concat "; // << str << "$" << nr;
  stringstream ss;
  ss << str << nr;
  cerr << "Post concat";
  return ss.str();
}

Any idea why?

(I will just use a method, overloading operators on standard types is probably a bad idea as it is likely to conflict with other modules. But damned if I can see what is wrong with this.)

Upvotes: 2

Views: 256

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

"MyKey" is not std::string. It's const char[6]. And for "MyKey" + ((long long) timev), your overloading operator won't be called. Instead, "MyKey" will decay to const char*, then "MyKey" + ((long long) timev) might get out of the bound of the array, which is UB.

The code is equivalent as:

const char* key = "MyKey";
string cname = key + ((long long) timev); // or key[((long long) timev)]

You could

string cname = string("MyKey") + ((long long) timev);

Upvotes: 6

Related Questions