-1

次のプログラムを使用して、ファイル記述子 '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);
                }                   
            }
        }
4

1 に答える 1

1

として宣言しuserInputていchar *ます。これにより、ほぼ確実に所有しておらず、書き込みできないランダムな場所を指すポインターが得られます。これが機能した場合、それは純粋な (不運な) 運によるものです。

userInputこれを修正する最も簡単な方法は、次のように配列として宣言することです。

char userInput[1024];.

これにより、 userInput は 1024 文字の配列になり、必要なだけ変更でき、具体的fgetsには書き込み用に渡すことができます。

別の方法は、mallocメモリを取得するために使用することです。

char *userinput = malloc(1024);

これを行う場合は、ポインタが指すメモリのサイズではなく、ポインタのサイズ (通常は 4 または 8) が得られるfgetsため、呼び出しも変更する必要があります。sizeof(userInput)次のようなものです:

fgets(userInput, 1024, stdin);

また、メモリを取得する場合は、使い終わったらmalloc呼び出す必要があります。free

free(userInput);
于 2013-11-04T20:58:18.107 に答える