georoot georoot - 3 months ago 34
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;
};


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

LEN:5
OG:hello
TC:hello�������������������q{
CShello


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

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

Answer

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.