用gets()读取char*会报"Core Dumped"错误(C语言)

Reading char* with gets() makes "Core Dumped" error (C language)

我正在尝试使用非固定字符数组读取用户输入,但是当我输入内容时它只是 软崩溃(没有崩溃 window)在键盘上。当我在在线 C 编译器上 运行 它时,它说 Segmentation fault (core dumped).

我的代码:

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

int validerNAS(char* userInput);

int main() {
    int valid = 0;
    char* userInput;

    do {
        printf("Enter 9 characters: ");
        gets(userInput);
        valid = validerNAS(userInput);
    } while (!valid);
    return 0;
}

int validerNAS(char* userInput) {
    if ((strlen(userInput) != 9))  {
        printf("Error! You must enter 9 characters\n\n");
        return 0;
    }
    return 0;
}

这里

char* userInput;

userInput 没有任何有效内存,因此您可以像

一样将一些数据放入其中
gets(userInput); /* this causes seg.fault because till now userInput doesn't have any valid memory */

所以要克服这个问题要么使用像

这样的字符数组
char userInput[100] = {0};

或者创建动态数组,然后将数据扫描到动态分配的内存中。

也不要使用 gets(),而是使用 fgets(),如 here

中所述

例如

char* userInput = malloc(SOME_SIZE); /* define SOME_SIZE, creating dynamic array equal to SOME_SIZE  */
fgets(userInput ,SOME_SIZE, stdin) ; /* scan the data from user & store into dynamically created buffer */

旁注,来自 fgets

的手册页

If a newline is read, it is stored into the buffer. A terminating null byte (aq[=22=]aq) is stored after the last character in the buffer.

因此通过调用 strcspn() 删除尾随的换行符。例如

userInput[strcspn(userInput, "\n")] = 0; 

一旦动态数组userInput的使用完成,不要忘记通过调用free()释放动态分配的内存以避免内存泄漏 .例如

free(userInput);