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

segmentation fault while copying the string buffer

我在复制字符串时遇到段错误。我已经尝试过类似的替代方案,但同样的问题仍然存在。

#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[=11=]";
    call(buff);
    return 0;
}

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

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

感谢您的帮助。

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

在做memcpy()之前做

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

您没有显示 struct iovec 定义,所以我假设其中的成员 iov_base 有足够的 space 来容纳字符串 (sendString).