strtok中的分段错误

liv*_*ove 2 c segmentation-fault

我一直在收到这个错误.我很确定它与内存分配有关,但我不太确定如何修复它.

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出给出"分段错误(核心转储)"

Gra*_*and 5

fgets(word, 100, stdin);
word = strtok(phrase, " ");
Run Code Online (Sandbox Code Playgroud)

你在这里有错误的参数.您正在拆分phrase未初始化的字符串,然后分配结果,word从而覆盖指向您先前分配的内存的指针.

您可能打算fgets将输入读入phrase而不是word.