Segmentation fault in strtok

杀马特。学长 韩版系。学妹 提交于 2019-12-23 23:52:01

问题


I keep getting that error. I am pretty sure it has something to do with memory allocation but i'm not quite sure how to fix it.

#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);
}

the out put gives "Segmentation fault (core dumped)"


回答1:


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

You have the parameters the wrong way round here. You're splitting the string in phrase which is uninitialized, and then you're assigning the result to word thus overwriting the pointer to the memory you previously allocated.

You probably intended for the fgets to read the input into phrase rather than word.



来源:https://stackoverflow.com/questions/8097074/segmentation-fault-in-strtok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!