Reputation: 383
I get a segmentation fault on line "pthread_t* tids = (pthread_t*) calloc(num_threads, sizeof(pthread_t));". I looked at the code for a day but cannot figure it out. I even delete all the content in the "child" function but it does not help.
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;
}
Upvotes: 0
Views: 642
Reputation: 70362
You are accessing an uninitialized variable, i
:
int i;
//for (i = 0; i < num_threads; i++) {
if (pthread_create(&tids[i], NULL, child, NULL)) {
Accessing an uninitialized variable results in undefined behavior. In this case, it could result in an invalid pointer passed in the first parameter to pthread_create()
, causing it to crash when the function attempts to dereference the pointer.
Upvotes: 3