I am trying to flush out a char
buffer by using strcpy(buffer, "")
. strcpy()
seems to be putting random numbers in the string. In gdb, I see the buffers (received_message
):
Before strcpy()
call:
(gdb) print received_message
$6 = "9210070627\000\000\000\000\000\000\000\000\000"
After strcpy()
call:
(gdb) print received_message
$8 = "\000\062\061\060\060\067\060\066\062\067\000\000\000\000\000\000\000\000\000"
Where \060
... \067
= 48 ... 65.
My strcpy()
call in the code is simply strcpy(received_message, "");
, so I am not sure what is going on.
I have solved the actual issue by just putting in a null terminator rather than trying to make the string empty since I know the length of the string, but I am still very curious about what is going on here.
EDIT: It seems that some people want some more background on why I am doing this. I was doing this as I am using zmq, which sends and received strings without the null terminator. I was running into a problem in a test where I was doing the following:
Send 1234
Receive 1234
Send 123
Receive 1234
Send 12345
Receive 12345
Send 1234
Receive 12345
What seemed to be happening is that I was reusing my buffer for receiving messages (received_message
), which was retaining values if the previous string was longer than the one that was being received.
To fix this, I wanted to "flush" the buffer, meaning I wanted to set it all to null characters. From reading some other answers, it seemed that strcpy(received_message, "")
would do the trick, as would recived_message[0] = 0
. However, neither of these would work as they only set the first character to null. I knew of the memset()
method of "flushing" the buffer, but read that it was a bit slower than something such as strcpy(received_message, "")
, so did not use it. The solution I figured out (and show below) avoids setting the whole array with memset()
, so I am a bit happier with it, although it likely makes no difference at all.
What confused me is the fact that this strcpy()
call replaced what was originally a number in a string by the individual numbers prefixed with \06
, which I has mistaken for ASCII characters such as \060
rather than 0 prefixed by \06
.
I have fixed the issue with receiving the message since zmq_recv()
returns the string length without the null terminator, so to put a null character at the end of the received message, we only need to do
int received_length = zmq_recv(request_socket, received_message, 20, 0);
received_message[received_length] = 0;
In this case, received message
is a 20-element array of char
and I'm worried about receiving messages longer than that in this case.
After solving the problem, I was still curious about what was going on with my strcpy()
call, although I was not correctly understanding what was happening. I am still curious why the numbers were being prefixed with \06
though.