Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

(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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading