2011-11-11 8 views
2

エラーが発生し続ける。私はそれがメモリ割り当てと関係があると確信していますが、私はそれをどのように修正するかについてはあまりよく分かりません。strtokのセグメンテーションエラー

#include <stdio.h> 
#include <stdlib.h> 
#include <limits.h> 
#include <string.h> 

char * VOWELS ="aeiouAEIOU"; 


void printLatinWord(char *a); 


int main(int argc, char **argv){ 
    char phrase[100]; 
    char *word = malloc(sizeof(char) *100); 

    printf("Enter the phrase to be translated: \n"); 

    fgets(word, 100, stdin); 
    printf("The phrase in Pig Latin is:\n"); 
    word = strtok(phrase, " "); 
    printLatinWord(word); 

    return 0; 
} 

void printLatinWord(char *word){ 
    while (strchr(VOWELS, *word) == NULL){ 
    char consonant = *word; 
    char *to=word, *from=word+1; 

    while (*from) 
     *to++=*from++; 
     *to=consonant; 
    } 
    printf("%say\n", word); 
} 

アウトプットは、あなたが丸いここパラメータに間違った方法を持っている「(ダンプコア)セグメンテーションフォールト」

+0

これは答えではありませんが、実際に['gdb'](http://www.gnu.org/s/gdb/)の使い方を学ぶべきです。発生する。 –

+0

障害が発生する前にどのくらい離れていますか?他の 'printf'文は実行されますか?ステップバイステップでデバッガを使いたいかもしれません。 – birryree

+0

これはちょっと偽ります: 'char * word = malloc(sizeof(char)* 100);'。次に、 'word'を' strtok() 'の戻り値に代入します。 – trojanfoe

答えて

5
fgets(word, 100, stdin); 
word = strtok(phrase, " "); 

を与えます。初期化されていないphraseの文字列を分割していて、結果をwordに代入すると、以前に割り当てたメモリへのポインタが上書きされます。

は、入力をwordではなくphraseに読み込むことをお勧めします。

+0

ty!それはそれを固定! – livelaughlove

+1

'word'にメモリを割り当てる必要はありません。 'strtok'を呼び出した後、' phrase'バッファの中のデータを指します。 –

関連する問題