Home > Net >  '\r\n' deletes the whole buffer when the length is too long
'\r\n' deletes the whole buffer when the length is too long

Time:03-04

I'm learning socket programming and there is a requirement in my project to put \r\n in every returned message. Something I notice that \r\n will delete the whole buffer when it exceeds some number of characters. For example, I have a code like this:

#include <iostream>

int main()
{
    std::string message = "mkdir homewor";
    const char *buffer = (message   "\r\n").c_str();

    std::cout << "message: " << message << std::endl;
    std::cout << "buffer: " << buffer << std::endl;
}

I run and it gives me the output like this:

message: mkdir homewor
buffer: mkdir homewor

I open the gdb and it gives me something like this:

message: "mkdir homewor"
buffer: 0x7fffffffdc50 "mkdir homewor\r\n"
  - *buffer: 109 'm'

Which is something I expect it.

But when the message is too long and I convert it to C-String, the whole buffer gets deleted. For example:

#include <iostream>

int main()
{
    std::string message = "mkdir homework"; // Just one more 'k' at the end
    const char *buffer = (message   "\r\n").c_str();

    std::cout << "message: " << message << std::endl;
    std::cout << "buffer: " << buffer << std::endl;
}

I run and it gives me the output:

message: mkdir homework
buffer:

gdb gives me this:

message: "mkdir homework"
buffer: 0x55555556aeb0 ""
  - *buffer: 0 '\000'

One more observation is that if the message has or exceeds the length of the message in the second example, the buffer will be deleted no matter what. Can anyone tell me what this problem is? I cannot get rid of \r\n because it's required in the project.

Thanks in advance.

CodePudding user response:

(message "\r\n") creates a new std::string, and it is backed with a pointer. This new std::string will get destroyed at the end of the full-expression.

So you should do this,

#include <iostream>

int main()
{
    std::string message = "mkdir homework"; // Just one more 'k' at the end
    std::string messageSuffixed = message   "\r\n";
    const char *buffer = messageSuffixed.c_str();

    std::cout << "message: " << message << std::endl;
    std::cout << "buffer: " << buffer << std::endl;
}
  • Related