Segfault when using strtok

Courtney Fennell

This program works fine if I comment out "printPigWord(temp);" and it tokenizes the words as it should with no problems but then once I add that line back, it won't do the next token. It will print 1 "pig latin" word and returns back to main and then I get a segmentation fault. I have no idea what causes it.

int main (void){
    char phrase[50];
    char *token, c, temp[20];
    int i=0;

    printf("Enter a phrase to be translated into pig latin: ");
    c = getchar();
    while( c != '\n'){
        phrase[i++] = c;
        c = getchar();
    }
    phrase[i] = '\0';

    token = strtok(phrase, " ");

    while(token != NULL){
        strcpy(temp, token);
        printPigWord(temp);
        token = strtok(NULL, " ");

    }

    return 0; /*Successful completion*/
}

void printPigWord(char token[20]){
    char first[1];
    char temp[20];

    /*save first letter */
    strncpy(first, token, 1);
    first[1] = '\0';

    /*add ay to end of first letter*/
    strcat(first, "ay");

    /*remove first letter of token*/
    strcpy(temp, &token[1]);

    /*add first letter+ay to end of token*/
    strcat(temp, first);

    /*print out token*/
    printf("%s\n", temp);

}
pbhd

Hmpf. first is only one chars long. You cannot concat stuff to it, otherwise you overwrite something else (e.g. temp)...

first[1] = '\0'; // already out of boundes

/*add ay to end of first letter*/
strcat(first, "ay"); // again, first can carry only one char

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related