gpt4 book ai didi

c - strcpy() 上的段错误;

转载 作者:行者123 更新时间:2023-11-30 14:58:01 25 4
gpt4 key购买 nike

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>


typedef struct client
{
int threadid;
int argc;
char *argv[3];
} client;

void exit(int status);
void error(char *msg);

void *threadClient(void *socket_desc);

int main(int argc, char *argv[])
{
client info[10];
pthread_t thread[10];

printf("%s\n%s\n%s\n", argv[0], argv[1], argv[2]);

// Error happens here

for (int i=0; i<=10; i++)
{
info[i].threadid = i;
strcpy(info[i].argv[0], argv[0]);
strcpy(info[i].argv[1], argv[1]);
strcpy(info[i].argv[2], argv[2]);
info[i].argc = argc;
printf("here");
if (pthread_create(&thread[i], NULL, threadClient, (void*)&info[i]) < 0)
{
perror("could not create thread");
return 1;
}
sleep(3);
}
pthread_exit(NULL);
return 0;

}

在循环期间,当我尝试将信息从 argv 复制到我的结构时,出现段错误。为什么会发生这种情况?

Program received signal SIGSEGV, Segmentation fault.__strcpy_sse2_unaligned () at ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S:296296 ../sysdeps/x86_64/multiarch/strcpy-sse2-unaligned.S: No such file or directory.

最佳答案

这里有两个问题。

首先,你的argv数组在你的 info结构体是一个指针数组。这些开始时未初始化。当您稍后调用strcpy时,将这些数组元素之一作为第一个参数,它期望该指针指向有效的内存。因此,您最终会取消引用未初始化的指针。这会调用 undefined behavior ,在本例中表现为段错误。

您需要为这些指针分配一些内容。您可以使用 strdup复制这些字符串:

info[i].argv[0] = strdup(argv[0]);
info[i].argv[1] = strdup(argv[1]);
info[i].argv[2] = strdup(argv[2]);

或者,如果您不打算修改这些值,则可以直接复制指针值:

info[i].argv[0] = argv[0];
info[i].argv[1] = argv[1];
info[i].argv[2] = argv[2];

第二个问题是循环中的一个差一错误:

for (int i=0; i<=10; i++){

因为你使用<= ,数组中的索引范围为 0 到 10。但是,数组只有 10 个元素(索引为 0 到 9),因此您写入的内容超出了数组的末尾。这也会调用未定义的行为。

将条件更改为 <如下:

for (int i=0; i<10; i++){

关于c - strcpy() 上的段错误;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43528034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com