C - 使用 strlen 时出现分段错误?

C - Segmentation fault when using strlen?

I'm getting a segmentation fault with using strlen.

我的函数:

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;
    }
}

我的scanf行有问题吗?在使用 strlen 之前我从来没有遇到过这种问题......所以我假设我可能没有将用户的输入正确读入 'userInput'.

改用char userInput[128];

scanf 需要一个指向有效内存的指针来将用户输入的内容放入。

 char * userInput;

上面的变量是一个指针,它没有指向任何地方(意思是没有内存位置)。

它应该包含一个地址来存储/检索数据。

因此,要么必须为此变量分配内存,要么使用 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;
}