下面的函数终止并在fgets
语句中给出了一个分段错误,我不知道原因:
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;
}
发布于 2021-11-27 09:24:38
您不能为具有自动存储持续时间的数组调用此函数,因为您正在尝试这样做
char maxstr[50];
//...
temp=maxstr;
free(temp);
您只能为指向动态分配内存的指针或空指针调用函数free。
也是这个调用
printf("%s",exp);
没有多大意义,因为指针exp
所指向的动态分配数组包含空字符串
exp = (char*)calloc(strlen(maxstr),sizeof(char));
看起来你的意思是这样的:
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;
}
发布于 2021-11-27 09:36:02
您的代码中存在多个问题:
fgets()
是否成功,这会导致文件末尾出现未定义的行为。exp = calloc(strlen(maxstr) + 1, 1);
并检查内存分配故障,要么使用exp = strdup(maxstr);
.temp = maxstr;
不复制字符串,您应该使用strcpy(exp, maxstr)
,或者使用同时执行分配和字符串复制的strdup()
。free(temp);
试图释放本地数组,导致未定义的行为。本地数组不需要被释放,当函数返回时,它的空间将被自动回收,因此被称为自动存储。由于您没有将读入maxstr
的字符串复制到分配的数组中,因此
return exp
返回指向空字符串的指针。以下是修改后的版本:
#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;
}
}
https://stackoverflow.com/questions/70133428
复制相似问题