2013-11-04 54 views
-1

我正在尝试使用以下程序从文件描述符'0'(STDIN)中读取用户输入。之前,它没有问题,但是在程序的其他部分发生了一些变化之后,它在读取输入时给我一个分段错误。我还删除了“FD_CLR(0,& readfds)”以查看它是否有效,但它不。你能检查问题出在哪里吗?从STDIN读取用户输入时出现分段错误

 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

如何为'userInput'声明,并且任何与完成它在达到这段代码之前? –

+0

@MarkkuK。对不起,我忘记了添加userInput声明语句。我刚刚编辑了我的第一篇文章,并在代码的开头添加了它。 – Amir

回答

1

你声明userInput作为char *。这给你一个指向一个随机位置的指针,你几乎肯定不会拥有它,也不能写入。如果这种情况发生,那么它就是纯粹的(坏)运气。

解决这个问题的最简单的方法是声明userInput作为数组,这样的:

char userInput[1024];

这将使用户输入一个由1024个字符组成的数组,您可以根据需要进行修改,特别是可以传入fgets中进行写入。

另一种方法是使用malloc得到一些记忆:

char *userinput = malloc(1024); 

如果你这样做,你也将不得不改变你对fgets呼叫,因为sizeof(userInput)将产生指针(通常为4或8的尺寸)而不是它指向的内存大小。因此,像:

fgets(userInput, 1024, stdin); 

此外,如果你从malloc得到的内存,你应该叫free当你用它做,所以:

free(userInput); 
相关问题