-4

I had written one coap client with libcoap to communicate with leshan server The issue is whenever I did a PUT request, first time it is correct, but if I do a PUT request from leshan, say 12345678 is the payload it adds a garbled value after that. Also if my next payload is longer, it behaves correctly and no garbled value is padded. if I again reduce payload size, the older size retains and garbled value padded to payload. code snippet of coap client:

  unsigned char *data;
  memset (data, '\0', sizeof(data));
  coap_get_data(request, &size, &data);

coap_get_data getting data from server

I entered payload in leshan server as sdsdsdsdasasasast

But the client received : sdsdsdsdasasasast�

And wireshark says : sdsdsdsdasasasast\201\005

I always did a memset before inserting data into arrays, still I don't know where it got such things padded after payload

Zim
  • 43
  • 2
  • 10
  • 2
    `unsigned char *data;` – where do you expect `data` to point to if you didn't initialize it? – The Paramagnetic Croissant Nov 25 '15 at 07:01
  • 1
    You need to allocate some memory for `data` - `malloc` perhaps? – Ed Heal Nov 25 '15 at 07:02
  • @TheParamagneticCroissant already did, forgot to mention here : data = (unsigned char*)malloc(sizeof(unsigned char)*128); memset (data, '\0', sizeof(data)); – Zim Nov 25 '15 at 07:06
  • @Zim can you guarantee that the server isn't sending you this garbage? – Magisch Nov 25 '15 at 07:27
  • @Magisch, that is where I am confused too. The data WIreshark captured shows sdsdsdsdasasasast\201\005 although in leshan it displayed that as sdsdsdsdasasasast� hence \201\005 which was not part of payload is added and showed in leshan as � – Zim Nov 25 '15 at 08:14
  • @Zim In that case your problem is most likely with the server code sending stuff rather than with what you posted. Ignoring the memory allocation issues (which you commented you fixed) your problem is then outside of the scope of the code you posted. – Magisch Nov 25 '15 at 08:15

1 Answers1

1

In your code,

memset (data, '\0', sizeof(data));

where data does not point to any valid memory, actually invokes undefined behavior.

Before copying into (or even reading from) a memory location pointed by a pointer, you need to make sure that the pointer points to a valid memory location allocated for that particular process.

Either use a compiler allocated memory, like

 unsigned char data[256] = {0};

or use malloc() or family to get the memory allocated to the pointer. Don't forget to free it afterwards,tho.

Dilip Kumar
  • 1,736
  • 11
  • 22