C - 从函数中的fgets()读取stdin的行 [英] C - read line from stdin with fgets() in function

查看:1386
本文介绍了C - 从函数中的fgets()读取stdin的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从stdin读取fgets()的行,我想在我的函数中使用fgets(),我认为这是问题所在。该字符串可能最长为1024个字符。当我运行这段代码时,我得到了分段错误(核心转储)。

I'm trying to read line from stdin with fgets(), I want to use fgets() in my function, which I think is the problem. The string could be max 1024 chars long. When I run this code I get "Segmentation fault (core dumped)"

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

#define MAX_SIZE 1025

void print_fgets();

int main()
{
    print_select();
    return 0;
}

void print_select()
{
    char *str;
    int length;

    while (fgets( str, MAX_SIZE, stdin)!=NULL)
    {
        length=strlen(str);

        if (length==MAX_SIZE-1 && str[length-1]!='\n')
        {
             printf("Error, line overeached buffer!\n");
             return 1;
        }

        if (str[length-1]=='\n')
             str[length-1]='\0';
        printf("%s\n", str);
    }
}


推荐答案

问题在于你试图写入 str 指针指向的位置。
最初它会指向一些垃圾地址(由于 char * str 未被初始化)。

The problem is that you try to write to the location that the str pointer points to. Initially it will point to some garbage address (due to char *str not being initialized).

您可以尝试使用基于堆栈的解决方案,而不是改变:

You can try a stack based solution instead by changing:

/* This is just a pointer */
char *str;

到:

/* This is a character array (on the stack) of size MAX_SIZE, initialized to zero */
char str[MAX_SIZE] = {0};

或者如果您想为数组动态分配内存,请改为:

Or if you want to allocate memory dynamically for the array, do this instead:

char *str;
str = calloc(1, MAX_SIZE);
if (str == NULL) {
    /* Failed to allocate memory */
}

... Your code

free(str);  /* You should always free dynamically allocated memory when you are done with it */
str = NULL; /* It's a good practice to point your pointer to NULL after it's free'd */

Don'不要忘记以 0 开头的数组索引,并转到 MAX_SIZE - 1 (在你的情况下)和NUL终止字符串必须以它结尾)。

Don't forget things like array index starting with 0 and goes to MAX_SIZE - 1 (in your case) and NUL termination (strings must end with it).

这篇关于C - 从函数中的fgets()读取stdin的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆