【问题标题】:Reading char* with gets() makes "Core Dumped" error (C language)使用 gets() 读取 char* 会导致“Core Dumped”错误(C 语言)
【发布时间】:2019-08-12 15:35:45
【问题描述】:

我正在尝试使用非固定字符数组读取用户输入,但当我在键盘上输入内容时,它只是 软崩溃(没有崩溃窗口)。当我在在线 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;
}

【问题讨论】:

  • 您希望输入存储在哪里?你还没有分配任何内存。除此之外 - 永远不要使用 gets,它不再是该语言的一部分并且已被弃用。
  • char* userInput; -> char userInput[100];。阅读 C 教科书中处理字符串的章节。
  • 而且validerNAS有一个小而明显的bug,我让你自己去发现。
  • @Eugene Sh.我尝试使用 scanf("%s", userInput) 但它会出现同样的错误。
  • OT: about:scanf("%s", userInput) 1) 始终检查返回值(不是参数值)以确保操作成功。在这种情况下,除 1 之外的任何返回值都表示发生了错误。 2) 当使用输入格式说明符 '%s' 和/或 '%[...]' 时,总是包含一个比输入缓冲区长度小 1 的 MAX CHARACTERS 修饰符,因为这些说明符总是将 NUL 字节附加到输入。这也避免了缓冲区溢出的任何可能性以及由此产生的未定义行为

标签: c memory segmentation-fault core


【解决方案1】:

这里

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的手册页

如果读取了换行符,则将其存储到缓冲区中。一种 终止空字节(aq\0aq)存储在最后一个字符之后 缓冲区。

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

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

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

free(userInput);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 2015-07-29
    相关资源
    最近更新 更多