我的Chatbot轮询功能无法正常工作, 我在线程处理程序上遇到分段错误,我使用gdb查看更多内容,这就是我得到的:
Thread 4 "St3veB0t" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff67c2700 (LWP 5957)]
0x0000555555557243 in poll_handler ()
(gdb) bt
#0 0x0000555555557243 in poll_handler ()
#1 0x00007ffff7bbd6db in start_thread (arg=0x7ffff67c2700)
at pthread_create.c:463
#2 0x00007ffff78e688f in clone ()
at ../sysdeps/unix/sysv/linux/x86_64/clone.S:95
函数poll_handler()
是这样的:
void * poll_handler(void * args)
{
FILE * fp;
struct VoteData vote;
struct PollHandlerData * data = (struct PollHandlerData *)args;
int res;
char * string = (char *)malloc(sizeof(char)*MAX_BUFFER);
sleep(60);
*data->status = 0;
*data->vote_count = 0;
if(!(fp = fopen("polls/votes.txt", "r")))
{
fprintf(stderr, "\nError in reading file\n");
if(!(fp = fopen("polls/votes.txt", "w+")))
{
fprintf(stderr, "\nError in creating file\n");
exit(EXIT_FAILURE);
}
}
vote = GetMostVote(fp);
strcpy(string, "PRIVMSG #st3ver0nix : Polling terminated, the majority voted: ");
strcat(string, vote.word);
strcat(string, "\r\n");
do{
res = write(data->sock, string, strlen(string));
}while(res < strlen(string));
fclose(fp);
free(string);
pthread_exit(NULL);
}
创建线程的函数是这样的:
void CreatePoll(int sock, char * message, char * poll_name, int * status, int * vote_count)
{
pthread_t tid;
struct PollHandlerData * data = (struct PollHandlerData *)malloc(sizeof(struct PollHandlerData));
char * name = (char *)malloc(sizeof(char)*MAX_BUFFER);
GetPollName(message, name);
sscanf(name, "%s", poll_name);
data->sock = sock;
data->status = status;
sscanf(poll_name, "%s", data->name);
pthread_create(&tid, NULL, poll_handler, (void *)data);
pthread_detach(tid);
free(name);
}
结构PollHandlerData
和VoteData
具有以下形式:
struct PollHandlerData
{
int sock;
char name[128];
int * status;
int * vote_count;
};
struct VoteData
{
char word[128];
int freq;
};
我真的不知道我的代码有什么问题。我正在使用POSIX pthreads。 请让我知道您是否需要有关代码的更多信息。
答案 0 :(得分:1)
根据poll_handler()
线程分配中的观察,vote_count
导致此崩溃:
*data->vote_count = 0;
在函数CreatePoll()
中创建变量vote_count
内的线程data
之前,指针未分配或未指向任何有效的指针,因为仅对变量data
执行了malloc它将具有任何垃圾值。因此,在访问无效指针时,它在poll_handler()
中崩溃了。
注意:vote_count
将具有垃圾值,如果这是该进程的有效指针,则可能不会使进程崩溃。