【问题标题】:How to copy a string into middle of character pointer如何将字符串复制到字符指针的中间
【发布时间】:2013-12-07 05:49:00
【问题描述】:

我有一个动态分配的 char 数组,其中包含 pre_padding_buffer(大小 8)和 post_padding_buffer(大小 6)。我需要将字符串复制到这样的字符指针:

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

填充不是可选的,并且是我与之通信的机器的规格所必需的(它可以填充空/垃圾数据,无论如何它都会被覆盖)。

目前这就是我正在做的事情。

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

分段错误必须表明我没有正确复制字符串。当您在前后插入填充时,正确的做法是什么?

【问题讨论】:

  • Seg Fault 总是由于访问内存超出范围或未分配内存。
  • 这是 C 还是 C++?选择一个。
  • ...但是,libwebsocket_write 不是异步的吗?在这种情况下,您不应该在完成他的任务之前释放()他的数据
  • #include&lt;stdlib.h&gt;了吗?
  • 如果这是C,那么do NOT cast the return value of malloc()

标签: c string pointers strcpy


【解决方案1】:

response_all_buf[LWS_SEND_BUFFER_PRE_PADDING + i] = async_string[i];

  • 在处理字符串或字符时不建议这样做。正如 0XF1 所建议的,您可以按照可以很好地控制 response_all_buf 的方法进行操作。

【讨论】:

    【解决方案2】:

    整洁的方法:

    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));
    

    或者,正如您所说的填充可以包含垃圾:
    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2011-11-01
      • 2010-09-27
      • 2015-01-17
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-27
      • 1970-01-01
      相关资源
      最近更新 更多