#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 ?