I'm trying to write a small plugin for X-Plane, to create a simple websocket server with libwebsocket. I'm able to connect to the websocket from Google Chrome, however, when I send data to the server, X-Plane immediately crashes.
I'm pretty certain the following code is causing the problem:
unsigned char *buf = (unsigned char*) malloc(LWS_SEND_BUFFER_PRE_PADDING + 13 + LWS_SEND_BUFFER_POST_PADDING);
buf = (unsigned char*) "Hello World!";
libwebsocket_write(wsi, buf, len, LWS_WRITE_TEXT);
free(buf);
I'm not a C programmer / specialist at all, but does the above seem to have a problem at all?
I've posted the full source on Gist: https://gist.github.com/josefvanniekerk/868432986f2f963a5583
With any sane interface, @iharob would be right - to be clear he/she is right about you misunderstanding string assignment.
However, libwebsockets is a bit 'special'. You need to copy the string into the
malloc()
'd arrayLWS_SEND_BUFFER_PRE_PADDING
bytes in. libwebsockets then overwrites the preceding bytes.So you want something like (assuming you are not trying to send the terminating zero on the string):
If you want to send the
NUL
as well:You need to copy the string, assignment doesn't work as you expect.
Instead of
you need
when you do the assignment, you make
buf
point to a static string literal, andfree()
is not possible in this case.Your program invokes undefined behavior because of that.
You need to include
<string.h>