Ildar
Ildar

Reputation: 5

encoding changes after conversion char* to string

I am reading a char[] from socket with this code:

char* Beam::receive_msg()
{   
    char szResponse[50] = "";
    int retVal = recv(clientSocket, szResponse, 50, 0);
    ...        

    printf("Got the response from server\n%s\n",szResponse);
    return szResponse;
}
char *temp = receive_msg();
string msg = string(temp);

I get the message in temp that I want - "(0.1,0.1)", but in string msg I got another string with cyrillic symbols.

Can you help me how to solve it?

Upvotes: 0

Views: 66

Answers (3)

Potatoswatter
Potatoswatter

Reputation: 137820

Although Jesse's answer is the best, the simplest solution is to change the buffer to static storage duration so it persists after the function call.

static char szResponse[50];

Although best practice is to always initialize variables, you might not write an initializer with szResponse. It will be zeroed anyway, and "" misleadingly causes it to appear to store a string, which it doesn't. Note that recv is not a string-based function, and it doesn't add a NUL terminator, so you should do so manually yourself. Otherwise the printf may cause a buffer overflow. (This isn't necessary if you receive directly into the underlying buffer of std::string.)

Also, static implements a global variable, this solution would render receive_msg not re-entrant. It couldn't be called simultaneously from two threads.

Avoiding C strings and buffers entirely in favor of std::string is definitely the best solution.

Upvotes: 1

ddz
ddz

Reputation: 526

Try:

char* Beam::receive_msg()
{   
    char szResponse = new char[50];
    int retVal = recv(clientSocket, szResponse, 50, 0);
    ...        

    printf("Got the response from server\n%s\n",szResponse);
    return szResponse;
}
char *temp = receive_msg();
string msg = string(temp);
delete(temp);

Or:

void Beam::receive_msg(char *szResponse)
{   
    int retVal = recv(clientSocket, szResponse, 50, 0);
    ...        

    printf("Got the response from server\n%s\n",szResponse);
}
char temp[50];
receive_msg(temp);
string msg = string(temp);

Upvotes: -1

Jesse Good
Jesse Good

Reputation: 52365

Your szResponse is a local variable on the stack. You are returning a pointer to a local variable, when you dereference that pointer you get undefined behavior as that memory is no longer valid once the function exits.

One solution would be to change your member function to return an std::string instead.

Also, make sure you are compiling with high warning levels, as I'm pretty sure most compilers will give a warning for this.

Upvotes: 2

Related Questions