The following code (part of a request-response loop in a networked server) works most of the time, but sometimes fails, in that the client will report it has gotten some weird other string (seemingly random bytes from locations nearby in memory in this functions, or null bytes).
string res = "";
if (something) {
res = "ok";
}
if (res.length() > 0) {
send_data((void*) res.c_str(), res.length());
}
In my mind, it would seem that both "" and "ok" are constant std:strings, and res is a pointer to either one of them, and as such the whole thing should work, but apparently that's not the case, so can someone please explain to me what happens here?
send_data()is nonblocking, and you are destroyingresbefore it completes?c_str()is only guaranteed to be valid until the next call to a non-constant member function ofres. Specifically, if res is destroyed by, e.g., going out of scope, then the value previously returned byres.c_str()is no longer valid.