Question

I have a silly problem while reading input with the following code.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>


void read(char*** query)
{
    *query = (char**) malloc ( sizeof(char*) );

    int f=0;
    int i=0,j=0,c;

    while((c=getchar())!=EOF)
    {
        if(!isalpha(c))
            continue;

        if(f==1)
            *query=(char**) realloc(*query,(i+1)*sizeof(char*));

        (*query)[i]=(char*) malloc(sizeof(char));
        (*query)[i][j]=tolower(c);
        j++;

        while( (c=getchar())!=EOF&&c!=' '&&c!='\t'&&c!='\n' )
        {

            (*query)[i]=(char*) realloc((*query)[i],(j+1)*sizeof(char));

            (*query)[i][j]=tolower(c);
            ++j;
        }

        (*query)[i][j]='\0';

        ++i;
        f=1;
        j=0;

        if(c==EOF)
        {
            *query=(char**) realloc(*query,(i+1)*sizeof(char*));
            query[i]=NULL;
            return;
        }
    }


    *query=(char**) realloc(*query,(i+1)*sizeof(char*));
    query[i]=NULL;

}

int main()
{

    char** query;
    int i=0;
    read(&query);

    while(query[i]!=NULL)
    {
        printf("%s\n",query[i]);
        i++;
    }

    return 0;
}

So, I want to input any number of strings consisting of alphabetic characters separated by any number of spaces and tabs along a single line then press enter and give EOF signal.(CTRL+D under linux terminal.) Then, it should output strings line by line fashion. The problem is when I enter 3 strings it gives segmentation fault, but when I enter more or less strings no problem. What might be the problem? Please, help!

Was it helpful?

Solution

query[i]=NULL; wrong. – BLUEPIXY

@BLUEPIXY: Good catch. Also, in the OP's logic, there should be a reallocation before

(*query)[i][j]='\0';

to make room for the null char. – M Oehm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top