从STDIN读取用户输入时出现分段错误

时间:2013-11-04 18:32:42

标签: c select network-programming user-input stdin

我正在尝试使用以下程序从文件描述符“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);
                }                   
            }
        }

1 个答案:

答案 0 :(得分:1)

您将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);
相关问题