我正在尝试使用以下程序从文件描述符“0”(STDIN)读取用户输入。之前,它没有问题,但在程序其他部分进行一些更改后,它在读取输入时给我一个分段错误。我还删除了“FD_CLR(0, &readfds)”以查看它是否有效,但它不起作用。请您检查一下问题出在哪里?
char *userInput;
FD_ZERO(&masterfds);
FD_SET(0, &masterfds);
FD_SET(udp_con, &masterfds);
maxfds = udp_con;
while(exit == false)
{
readfds = masterfds;
selectFunc = select(maxfds+1, &readfds, NULL, NULL, &tv);
if(selectFunc < 0)
{
message("error in select");
exit = true;
}
else if(selectFunc == 0) //If there is a timeout
{
}
else //If a file descriptor is activated
{
if(FD_ISSET(udp_con, &readfds)) //If there is an activity on udp_con
{
/*read the udp_con via recvfrom function */
}
if(FD_ISSET(0, &readfds)) //If There is an input from keyboard
{
/* When it reaches to this part, the program shows a "segmentation fault" error */
fgets(userInput, sizeof(userInput), stdin);
int len = strlen(userInput) - 1;
if (userInput[len] == '\n')
{
userInput[len] = '\0';
}
string str = userInput;
cout<<"The user said: "<<str<<endl;
commandDetector(str);
FD_CLR(0, &readfds);
}
}
}
您将
userInput
声明为 char *
。这为您提供了一个指向某个随机位置的指针,您几乎肯定不拥有该位置并且无法写入该位置。如果这成功了,那纯粹是运气不好。
解决此问题的最简单方法是将
userInput
声明为数组,例如:
char userInput[1024];
.
这将使 userInput 成为一个 1024 个字符的数组,您可以根据需要对其进行修改,特别是可以传递到
fgets
以便写入。
另一种方法是使用
malloc
来获取一些内存:
char *userinput = malloc(1024);
如果这样做,您还必须更改对
fgets
的调用,因为 sizeof(userInput)
将产生指针的大小(通常为 4 或 8),而不是它指向的内存的大小。所以类似:
fgets(userInput, 1024, stdin);
此外,如果您从
malloc
获取内存,则在完成后应该调用 free
,所以:
free(userInput);