复制字符串缓冲区时出现分段错误

时间:2016-05-06 10:08:23

标签: c string fault

我在复制字符串时遇到了seg错误。我尝试过类似的替代品,但同样的问题占上风。

#if 0
       struct msghdr {
               void *msg_name; /* Socket name */
               int msg_namelen; /* Length of name */
               struct iovec *msg_iov; /* Data blocks */
              __kernel_size_t msg_iovlen; /* Number of blocks */
              void *msg_control; /* Per protocol magic (eg BSD file descriptor passing) */
              __kernel_size_t msg_controllen; /* Length of cmsg list */
              unsigned int msg_flags;
};
#endif


void call(char sendString[] )
{
    struct msghdr msg;
    int rc;
    struct sockaddr_in server_addr;
    memset(&server_addr, 0 , sizeof(struct sockaddr_in));
    memset(&msg, 0 , sizeof(struct msghdr));
    msg.msg_name = (void *)&server_addr;
    msg.msg_namelen = sizeof(struct sockaddr_in);
    printf("sendString = %s\n", sendString);
    //msg.msg_iov->iov_base = (void *)sendString; // seg fault here
    memcpy(msg.msg_iov->iov_base, sendString, strlen(sendString)); // seg fault here
    printf("len = %d\n", strlen(sendString));
    #if 0
    msg.msg_iov->iov_len = strlen(sendString);
    msg.msg_iovlen = 1;
    msg.msg_control = NULL;
    msg.msg_controllen = 0;
    msg.msg_flags = 0;
    #endif
    printf("rc = %d\n", rc);

}

int
main(int argc, char **argv){
    char buff[32] = "Hello\0";
    call(buff);
    return 0;
}

我已尝试过两种情况,并在两行中​​都出现了分段错误:

msg.msg_iov->iov_base = (void *)sendString;
memcpy(msg.msg_iov->iov_base, sendString, strlen(sendString));

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

msg.msg_iov是一个指针,并且没有为此指针分配内存,并且您正尝试取消引用它,这将导致未定义的行为。

在执行memcpy()之前

msg.msg_iov = malloc(sizeof(struct iovec));

您尚未显示struct iovec定义,因此我假设其中的成员iov_base有足够的空间来容纳字符串(sendString)。