简体   繁体   中英

C - Segmentation fault when using strlen?

I'm getting a segmentation fault with using strlen.

My function:

void myFunction() 
{
    int counter = 0;
    char * userInput;
    bool validInput = true;

    while (1) 
    {
        validInput = true;
        printf("\nEnter a word: ");
        scanf("%s", userInput);

        for(counter = 0; counter < strlen(userInput); counter++)
        {
            if (islower(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
            if (isalpha(userInput[counter]) == 0)
            {
                validInput = false;
                break;
            }
        }

        if (!validInput)
        {
            printf("Please enter a wordcontaining only lower-case letters.\n");
            continue;
        }

        // Do something
        break;
    }
}

Is there something wrong with my scanf line? I've never had this sort of issue before with using strlen... so I assume maybe I'm not reading the user's input correctly into 'userInput'.

 char * userInput;

The above variable is a pointer , and it is pointing to nowhere (Mean no memory location ) .

It should contain a address to store / retrieve data .

So either you must allocate memory for this variable or use strdup

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

int main(int argc,char *argv[])
{
    char *inputStr; //wrong.
    char inputStrArray[100]; //correct
    char *inputStrPtr = malloc(sizeof(char)*100) ;//OK but dont forget to free the memory after use
    int condition = 1;

    while(condition )
    {
        printf("Please enter a string :");
        //scanf("%s",&inputStr); //wrong
        //printf(inputStr);
        scanf("%s",inputStrArray);
        printf("Ok I got it %s \n",inputStrArray);
        printf("Please enter one more time a string: ");
        scanf("%s",inputStrPtr);
        printf("Now I got it %s \n",inputStrPtr);
        condition = 0;

    }
    free(inputStrPtr);
    inputStrPtr = NULL; //try not to use it anywhere else
    return 0;
}

Use char userInput[128]; instead.

scanf expects a pointer to valid memory to put the contents of the users input in to.

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