我的聊天机器人轮询功能无法正常工作,我在线程处理程序上遇到分段错误,我使用 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 filen");
if(!(fp = fopen("polls/votes.txt", "w+")))
{
fprintf(stderr, "nError in creating filen");
exit(EXIT_FAILURE);
}
}
vote = GetMostVote(fp);
strcpy(string, "PRIVMSG #st3ver0nix : Polling terminated, the majority voted: ");
strcat(string, vote.word);
strcat(string, "rn");
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 线程。如果您需要有关代码的更多信息,请告诉我。
poll_handler()
中的观察,线程分配是为造成此崩溃vote_count
完成的:
*data->vote_count = 0;
在函数CreatePoll()
创建线程之前vote_count
data
变量内的指针未分配或未指向任何有效指针,因为只有 malloc 对变量 data
完成并且它将具有任何垃圾值。因此,它在访问无效指针时在poll_handler()
中崩溃。
注意:vote_count
将有一个垃圾值,如果这是进程的有效指针,则可能不会使进程崩溃。