c - 为什么 gets() 读取的字符比我在用 calloc() 初始化它时设置的限制更多?

标签 c memory-management dynamic calloc gets

<分区>

我正在尝试获取动态内存分配,我只想让我的程序从用户的字符串中获取一个字符串和应该打印的最大字符数,然后只输出字符串直到我用 calloc 分配的字符数。当我运行该程序时,它完全无视我使用 calloc() 为它设置的限制,只是打印出整个字符串。

我尝试使用 malloc 但得到了相同的结果。另外,当我第一次尝试打印输入的文本时,我取消了对文本的引用,但它导致程序在您输入要打印的字符串后停止。

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

int main()
{
    int max;
    char *text = NULL;

    printf("\n\n");
    printf("Please enter the limit for the string as a positive integer: \n");
    scanf("%d", &max);

    text = (char *)calloc(max, sizeof(char));

    if (text != NULL)
    {
        printf("Please enter the string you want printed: \n");
        scanf(" "); //read in next character so it pauses
        gets(text);

        printf("Inputted text is : %s\n", text);
    }

    free(text);
    text = NULL;


    return 0;
}

是的,我知道,我收到了 gets 不安全的警告,但我是从教程中观看的,并且讲师的版本已构建并运行良好。即使我使用 scanf 将字符串读入文本,结果也是一样的。


使用 fgets() 修改代码:

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

int main()
{
    int max;
    char *text = NULL;

    printf("\n\n");
    printf("Please enter the limit for the string as a positive integer: \n");
    scanf("%d", &max);

    text = (char *)calloc(max, sizeof(char));

    if (fgets(text, max, stdin))
    {
        printf("Please enter the string you want printed: \n");
        fgets(text, max, stdin);
        text[strcspn(text, "\n")] = '\0';

        printf("Inputted text is : %s\n", text);
    }

    free(text);
    text = NULL;


    return 0;
}

我更改了我的代码以使用 fgets 并进行了一些更正。它返回的字符比用户输入的“最大值”少 1 个。另外,使用 fgets 是否意味着我不需要为 calloc 操心?

最佳答案

当你分配内存并将其分配给一个指针时,没有办法从手中的指针推断出内存的大小。所以 gets 没有机会(因此不会检查)它是否会超过您保留的内存量。顺便说一句:gets 不再是 C 标准的一部分(自 C11 起)。请改用 fgets 并将您的 max 作为参数传递:

if (fgets(text, max, stdin)) {
   // something successfully read in
   text[strcspn(text, "\n")] = '\0';
}

请注意,与 gets 相比,fgets 会保留所有输入的新行并将其保留在 text 的末尾。要摆脱这种情况,您可以使用 text[strcspn(text, "\n")] = '\0',这将使字符串在换行符(如果有)处结束。

关于c - 为什么 gets() 读取的字符比我在用 calloc() 初始化它时设置的限制更多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54173090/

相关文章:

通过命令提示符输入时, 'tab' 键的清晰度

c - 关于在 C 中打印字符

c - #include 在代码中间

swift - Swift 中奇怪的内存行为

objective-c - NSURLConnection 泄漏?

php - Jekyll 的动态内容

c - C中void指针的指针运算

unix - vm.max_map_count和mmapfs

angular - 如何重新加载/刷新动态注入(inject)的组件 Angular 6

javascript - Ember.js 动态链接