georoot georoot - 8 months ago 59
C++ Question

String to const char * in c++ puts garbage at end

I have a struct that needs to store const char * for later. The string gets destroyed by then. The code that i have till now for the same is

HttpRequest* send(string reply)
int len = strlen(reply.c_str());
char *buffer = new char[len+1];
strncpy(buffer, reply.c_str(), len);
cout << "LEN:"<<reply.length()<<endl;
cout << "OG:"<<reply<<endl<<"TC:"<<buffer<<endl<<"CS"<<reply.c_str()<<endl;
this->res.response = "test";
return this;

is the char * that i want to store the value in. The output from cout that i am getting is


This behavior is pretty strange to me. Can someone please explain what i am doing wrong. Also the above code shows me using
but i am getting the same result using
in c++ also.

Also it is worth mentioning that this happens only the first time that i invoke this, after that it goes fine.


You never put the null terminator:

char *buffer = new char[len+1];
strncpy(buffer, reply.c_str(), len);
buffer[len] = 0; // <-- HERE

strncpy doesn't add it.