I have the following packet payload from a websocket Im parsing in c.
81 82 ce 5d 4d ac bf 57
I received it with a unsigned char array like this.
unsigned char array[256];
recv(new_socket, array, sizeof(array),0);
But when i iterate over it to check it out it gets funky...
while(i != 256){
printf("%x\n", array[i]);
i ;
}
#output:
81
82
ce
5d
4d
ac
bf
57
40
0
0
0
0
0
0
0
40
... more zeros and bad hexes
It looks like the first few are fine but then something starts adding nulls and random weird hexes to my buf. This seems simple to me but i'm new. Can you guys help me fix it?
CodePudding user response:
Assuming you are using the standard recv function from Linux, the function returns a value of type ssize_t
that specifies how many bytes it received. You should look at the return value and only print that many bytes. If you print more bytes than that, you are just printing uninitialized bytes from your array, so they could be anything.
You could make your output cleaner and help avoid undefined behavior by initializing your array with zeros when you define it:
unsigned char array[256] = {};