我在线路上遇到分段错误“pthread_t * tids =(pthread_t *)calloc(num_threads,sizeof(pthread_t));”。我查看了一天的代码,但无法弄明白。我甚至删除了“子”功能中的所有内容,但它没有帮助。
int main(int argc, char* argv[]) {
int sockfd, newsockfd, clilen;
struct sockaddr_in serv_addr, cli_addr;
int port_num, num_threads = 5;
switch (argc) {
case 3:
num_threads = atoi(argv[2]);
case 2:
port_num = atoi(argv[1]);
break;
default:
fprintf(stderr, "Usage: %s <port_number> <num_threads>\n", argv[0]);
return -1;
break;
}
queue_t *q;
// the queue is unbounded if give a queue size of 0
queue_init(&q, 0);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
return 1;
}
bzero((char*) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons((short) port_num);
if (bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0)
perror("ERROR on binding");
listen(sockfd,5);
printf("numofthreads: %d\n", num_threads);
pthread_t* tids = (pthread_t*) calloc(num_threads, sizeof(pthread_t));
if (tids == NULL) {
printf("ERROR: failed to allocate memory!\n");
}
int i;
//for (i = 0; i < num_threads; i++) {
if (pthread_create(&tids[i], NULL, child, NULL)) {
perror("ERROR");
close(newsockfd);
return 1;
}
//}
while(1) {
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
perror("ERROR on accept");
queue_push(q, newsockfd);
//close(s_info.newsockfd); TODO
}
//clean up
clean_up(q);
free(tids);
free(output_dir);
return 0;
}
答案 0 :(得分:3)
您正在访问未初始化的变量i
:
int i;
//for (i = 0; i < num_threads; i++) {
if (pthread_create(&tids[i], NULL, child, NULL)) {
访问未初始化的变量会导致未定义的行为。在这种情况下,它可能导致在第一个参数中传递给pthread_create()
的无效指针,导致它在函数尝试取消引用指针时崩溃。