Thomas G
Thomas G

Reputation: 113

Segmentation Fault taking user input

I'm running a simple infinite loop that needs to take in user input and split it into an array. When I try to display the elements of the array I get a seg fault. This is my code.

while(1){
        int tokenCount = 1;
        char* usrInputStr = NULL;
        char* buffer;

        scanf ("%[^\n]%*c", usrInputStr);

        int len = strlen(usrInputStr);

           for (int i = 0; i <len ; ++i) {
               if(isspace(usrInputStr[i])) tokenCount++;
           }

        char* currentTokens[tokenCount+1];
        int index = 0;
        buffer = strtok(usrInputStr, " ");
        while(buffer != NULL){
            currentTokens[index] = buffer;
            index++;
            buffer = strtok(NULL, " ");
        }
        for (int i = 0; i < index+1; ++i)
        {
            currentTokens[i];
        }


    }//end of backbone while

    return 0;
}

Any idea where I'm going wrong, the same code was working fine in a .cpp file, when compiled with g++.

Upvotes: 0

Views: 1499

Answers (2)

srhaider
srhaider

Reputation: 17

You have not allocated any memory location to char * usrInputStr and scanning something to it which is actually a null pointer. which resulted you some segmentation fault error. You just assign some dynamic memory to it. For Example:-

char * usrInputStr = (char *) malloc (50*sizeof(char));

Upvotes: 0

R Sahu
R Sahu

Reputation: 206737

You have not allocated memory for usrInputStr after you initialized it with:

char* usrInputStr = NULL;

and then you proceed to use it in:

scanf ("%[^\n]%*c", usrInputStr);

Upvotes: 3

Related Questions