简体   繁体   中英

C Segmentation fault using strtok

I've created a program that is suppose to fully justify text which is input into the class except when transferring the words to output, errors are shown and I am unsure why but it ends up end up causing a segmentation fault when running the program. What is causing this error and how can I fix this?

void format_text(int * option_stats, unsigned width, char * text)
{
    int x = 0, y = 0, spaces = 0, remain = 0, j = 0;
    char* words, output;
    char temp[200] = {" "};
    words = strtok(text, " ");
    while (words != NULL)
    {
        if (y + strlen(words) < width)
        {
            strcpy(temp, words);
            strcat(temp, " ");
            y += strlen(words) +1;
            spaces += 1;
            words = strtok(NULL, " ");
        }
        else if(y + strlen(words) ==  width)
        {
            strcpy(temp, words);
            printf("%s\n", temp);
            y = 0;
            spaces = 0;
        }
        else if(spaces > 1)
        {
            remain = width - (y - 1);
            j = remain % (spaces - 1);
            remain = (remain-j)/(spaces-1);
            output = strtok(temp, " ");
            while (output != NULL)
            {
                printf("%c", output);
                if(j > 0)
                {
                    printf(" ");
                    j--;
                }
                output = strtok(NULL, " ");
                y = 0;
                spaces = 0;
                words = strtok(NULL, " ");
            }
        }
        x += (strlen(words) + 1);
    }
}

You are using output as a char * in

while (output != NULL){

and

output = strtok(NULL, " ");

But output is declared as simple char

char* words, output;

Take a look to Question 1.5 of C-FAQ

变量outputchar类型

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM