2013-11-04 55 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); 
相關問題