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?

6
  • Seg Fault is always due to accessing memory out of bound or unallocated memory. Commented Nov 22, 2013 at 11:12
  • 3
    Is this C or C++? Pick one. Commented Nov 22, 2013 at 11:12
  • 2
    ...but, isn't libwebsocket_write async? in this case you shouldn't free( ) his datas before it finishes his task Commented Nov 22, 2013 at 11:14
  • Did you #include <stdlib.h>? Commented Nov 22, 2013 at 11:16
  • 3
    If this is C, then do NOT cast the return value of malloc(). Commented Nov 22, 2013 at 11:16

2 Answers 2

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));
Sign up to request clarification or add additional context in comments.

Comments

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.