-2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_INPUT_LENGTH 1024

char *readline(FILE* fp, int max_length)
{
    //The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    int len = 0;
    int current_max = max_length;

    str = (char*)malloc(sizeof(char)*current_max);
    if(!str)
        return str;

    while((ch = fgetc(fp))!=EOF)
    {
        /* Separate newline handling from EOF handling */
        if((char)ch == '\n')
        {
            str[len] = '\0';
            return str;
        }
        str[len++] = ch;

        if(len == current_max)
        {
            current_max = current_max + max_length;
            str = realloc(str, sizeof(char)*current_max);
            if(!str)
                return str;
        }
    }
    str[len] = '\0';

    return str;
}


int main(void)
{
    char *input, *token;

    input = readline(stdin, MAX_INPUT_LENGTH);

    printf("BEFORE\n");
    token = strtok(input, " "); //Segmentation Fault Here
    printf("AFTER"); //control never reaches here on " " or "\n" input.
}

In the above snippet, I am trying to tokenize strings on whitspace as delimiter. Whenever I give input as a newline(press ENTER) or a sequence of whitespaces, the strtok() call segfaults. From what I understand, it should return NULL which I should be handling in sanity check later, but that is not really happening.

Please help me, what am I missing here ?

bawejakunal
  • 1,678
  • 2
  • 25
  • 54

1 Answers1

1

Your analysis of where the fault is occurring is incorrect

printf("AFTER"); //control never reaches here on " " or "\n" input.

Actually, control does reach there. You just don't see the "AFTER" message because there's no newline or flush there. Change the code to this and the mystery will go away:

printf("AFTER\n");

I'll bet you couldn't replicate the fault with your MCVE because it does reach the end of main, which flushes output. You forgot the "V" in MCVE. You need to verify that it replicates the problem.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278