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

C-使用strlen时出现分段错误?,c,strlen,C,Strlen,我在使用strlen时遇到了一个分段错误 我的职能: void myFunction() { int counter = 0; char * userInput; bool validInput = true; while (1) { validInput = true; printf("\nEnter a word: "); scanf("%s", userInput); for(c

我在使用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;
    }
}
void myFunction()
{
int计数器=0;
字符*用户输入;
布尔有效输入=真;
而(1)
{
validInput=true;
printf(“\n输入一个单词:”);
scanf(“%s”,用户输入);
用于(计数器=0;计数器

我的扫描线有问题吗?我以前在使用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;
}
#包括
#包括
int main(int argc,char*argv[])
{
char*inputStr;//错误。
字符输入数组[100];//正确
char*inputstrprprtr=malloc(sizeof(char)*100);//可以,但使用后不要忘记释放内存
int条件=1;
while(条件)
{
printf(“请输入字符串:”);
//scanf(“%s”,&inputStr);//错误
//printf(inputStr);
scanf(“%s”,输入阵列);
printf(“好的,我得到了%s\n”,inputStrArray);
printf(“请再次输入字符串:”);
scanf(“%s”,inputstrpt);
printf(“现在我得到了%s\n”,inputstrpt);
条件=0;
}
免费(inputStrPtr);
inputStrPtr=NULL;//尽量不要在其他任何地方使用它
返回0;
}

您没有为
userInput
未定义的行为分配任何内存,以便在对象的值不确定时使用具有自动存储持续时间的对象的值。您正在传递一个野生指针,指向
scanf()
,然后指向
strlen()
;任何事情都有可能发生。您需要传递一个指针,该指针指向要扫描的字符串的足够存储空间。啊,好的,谢谢,我将尝试。。。有道理!仍在尝试使用CUse char
userInput[128]取而代之。然后用户输入150个字符的输入…这是一个基本的例子-printf说输入一个单词,我不记得任何单词超过128个字符。你也可以做char*userInput=NULL。然后在每次GetCy之前,userInput=realloc(userInput,sizeof(char)*(++userInputSize)),您还应该防止缓冲区溢出,例如
scanf(“%99s”,inputStrArray)