首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么这个fgets函数会给我一个分段错误?

为什么这个fgets函数会给我一个分段错误?
EN

Stack Overflow用户
提问于 2021-11-27 09:09:09
回答 2查看 36关注 0票数 1

下面的函数终止并在fgets语句中给出了一个分段错误,我不知道原因:

代码语言:javascript
运行
复制
const char* display_exp(FILE* fp){

    char maxstr[50];
    char* temp;
    char* exp;
    fgets(maxstr,sizeof(maxstr),fp);

    exp = (char*)calloc(strlen(maxstr),sizeof(char));
    temp=maxstr;

    free(temp);

    printf("%s",exp);

    return exp;
}
EN

回答 2

Stack Overflow用户

发布于 2021-11-27 09:24:38

您不能为具有自动存储持续时间的数组调用此函数,因为您正在尝试这样做

代码语言:javascript
运行
复制
char maxstr[50];

//...

temp=maxstr;

free(temp);

您只能为指向动态分配内存的指针或空指针调用函数free。

也是这个调用

代码语言:javascript
运行
复制
printf("%s",exp);

没有多大意义,因为指针exp所指向的动态分配数组包含空字符串

代码语言:javascript
运行
复制
exp = (char*)calloc(strlen(maxstr),sizeof(char));

看起来你的意思是这样的:

代码语言:javascript
运行
复制
const char * display_exp(FILE *fp)
{
    char maxstr[50] = { 0 };

    char *exp = NULL;

    if ( fgets(maxstr,sizeof(maxstr),fp) != NULL )
    {
        maxstr[ strcspn( maxstr, "\n" ) ] = '\0';

        char *exp = malloc( strlen(maxstr) + 1 );
        if ( exp != NULL ) strcpy( exp, maxstr );
    }

    return exp;
}
票数 2
EN

Stack Overflow用户

发布于 2021-11-27 09:36:02

您的代码中存在多个问题:

  • 您不会测试fgets()是否成功,这会导致文件末尾出现未定义的行为。

  • 您必须为空终止符分配一个额外的字节。要么使用exp = calloc(strlen(maxstr) + 1, 1);并检查内存分配故障,要么使用exp = strdup(maxstr);.

  • assigning temp = maxstr;不复制字符串,您应该使用strcpy(exp, maxstr),或者使用同时执行分配和字符串复制的strdup()

  • free(temp);试图释放本地数组,导致未定义的行为。本地数组不需要被释放,当函数返回时,它的空间将被自动回收,因此被称为自动存储。

由于您没有将读入maxstr的字符串复制到分配的数组中,因此

  • return exp返回指向空字符串的指针。

以下是修改后的版本:

代码语言:javascript
运行
复制
#include <stdio.h>
#include <string.h>

char *display_exp(FILE *fp) {
    char maxstr[50];

    if (fgets(maxstr, sizeof(maxstr), fp)) {
        // return an allocated copy of the line read from the user
        // if the line read has fewer than 49 characters and ends with
        // a newline, this newline is present in the string. You may
        // want to remove it by uncommenting this:
        //maxstr[strcspn(maxstr, "\n")] = '\0';
        return strdup(maxstr);
    } else {
        // fgets encountered a read error or the end of file.
        return NULL;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70133428

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档