2

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?

3
  • 7
    Is it possible that your send_data() is nonblocking, and you are destroying res before it completes? Commented Mar 22, 2011 at 13:44
  • 1
    That's right on the money. I'm using 0MQ here, and I was experimenting with the non-copying way of sending data, but obviously that doesn't work correctly in this case. Thanks! Commented Mar 22, 2011 at 13:55
  • The data pointed to by the return value from c_str() is only guaranteed to be valid until the next call to a non-constant member function of res. Specifically, if res is destroyed by, e.g., going out of scope, then the value previously returned by res.c_str() is no longer valid. Commented Mar 22, 2011 at 14:44

2 Answers 2

6

You probably forgot to send the null-terminator to denote the end of the string:

send_data((void*) res.c_str(), res.length()+1);
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't that at least have given me something mostly like the string I wanted to send, but with added garbage? That was not the case here (which is kind of implied but not entirely clear in my question).
Yes - except in the case of the empty string, where nothing would have been send (due to the if clause).
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.