1

I have a dynamically allocated char array with pre_padding_buffer (size 8) and post_padding_buffer (size 6). I need to copy the string over to a character pointer like this:

[ ][ ][ ][ ][ ][ ][ ][ ][e][x][a][m][p][l][e][ ][ ][ ][ ][ ][ ]

The paddings are not optional and required by the specs of a machine I'm communicating with (it can be filled with empty/garbage data, it's overwritten anyways).

Currently this is what I'm doing.

unsigned char *async_string = get_async_string();

unsigned char *response_all_buf = (unsigned char*)malloc(LWS_SEND_BUFFER_PRE_PADDING + strlen(async_string) + LWS_SEND_BUFFER_POST_PADDING);

//Copy string
int i = 0;
for (i = 0; i < strlen(async_string); i++) {
    response_all_buf[LWS_SEND_BUFFER_PRE_PADDING + i] = async_string[i];
}

libwebsocket_write(wsi,respones_all_buf,strlen(async_string),LWS_WRITE_TEXT);
free(response_all_buf); //<-- Segmentation fault here

Segmentation fault must indicate that I'm not copying the string correctly. What's the correct way of doing this when you have paddings to insert before and after?

TtT23
  • 6,876
  • 34
  • 103
  • 174

2 Answers2

1

The neat method:

response_all_buf = malloc(8 + strlen(async_string) + 6);
memset(response_all_buf, ' ', (8 + strlen(async_string) + 6));
memcpy(response_all_buf + 8, async_string, strlen(async_string));

Or, as you say padding can contain garbage:
You can do it this way:

response_all_buf = malloc(8 + strlen(async_string) + 6);
memcpy(response_all_buf + 8, async_string, strlen(async_string));
0xF1
  • 6,046
  • 2
  • 27
  • 50
0

Firs of all response_all_buf[LWS_SEND_BUFFER_PRE_PADDING + i] = async_string[i];

  • This is not advisable when you are dealing with strings or characters . As suggested by 0XF1 you can follow the approach where you have the control over the response_all_buf very well .
Srikanth
  • 447
  • 2
  • 8