我找不到此源代码中发生段错误的地方。
我正在用C语言制作UNIX http服务器。 使用pthread和响应函数(此代码为Refered())
我尝试检查缓冲区大小(标题,请求,文件,路径)。 并将pthread更改为fork(),但这没关系。
当我使用测试html文件时,效果很好。 但会在意外的时间中断。
while (1)
{
new_socket = (int *)malloc(sizeof(int));
if ((*new_socket = accept(create_socket, (struct sockaddr *)&address, &addrlen))==-1){
perror("accept");
exit(1);
}
pthread_create(&tid, NULL, threadfunc, (void*)new_socket);
pthread_detach(tid);
}
这是main()中的接受部分。
recv(*new_socket, buffer, 1024, 0);
printf("%s\n", buffer);
strcpy(getPath,basicpath);
strtok(buffer," ");
strcpy(openfilename,strtok(NULL," "));
if(strcmp(openfilename,"/") == 0)
strcpy(openfilename,"/index.html");
strcat(getPath,openfilename);
refered(*new_socket,getPath);
free(vargp);
return NULL;
if(((fd = open(filename, O_RDONLY)) < -1) || (fstat(fd, &filestat) < 0))
{
printf("Error in measuring the size of the file\n");
}
else
sprintf(filesize, "%zd", filestat.st_size);
if((fp = fopen(filename,"r")) == NULL)
{
strcpy (header_buff, "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nContent-Type: text/plain\r\nConnection: keep-alive\r\n\r\n");
write (ns, header_buff, strlen(header_buff));
}
else
{
strcpy (header_buff, "HTTP/1.1 200 OK\r\nContent-Length: ");
strcat (header_buff, filesize);
strcat (header_buff, "\r\nContent-Type: */* \r\nConnection: keep-alive\r\n\r\n");
fread (file_buff, sizeof(char), filestat.st_size + 1, fp);
write (ns, header_buff, strlen(header_buff));
write (ns, file_buff, filestat.st_size);
fclose(fp);
}
close(ns);
这是响应部分。
我想找到分段错误(核心转储)发生的地方。