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?
You probably forgot to send the null-terminator to denote the end of the string:
send_data((void*) res.c_str(), res.length()+1);
Your code is okay, I suppose there's some memory corruption in your program.
"" and "ok" are actually zero-terminated buffers of type 'const char *', not strings. When you assign them to your string all their data is copied inside string internal buffer, not including last char which is zero, so
res = "";
will clear internal string buffer, and res.length() will become 0.
res.c_str() will return the address of that buffer, not the address of "" or "ok" literals.
精彩评论