问题描述
我正在 Linux 64 位机器上编译。
运行 gcc struct-string-gates.c && ./a.out
提供以下意外输出:
Val: '0',Name: '123 -> x'
但是,如果我注释掉 while(fgets..
循环,我会得到以下预期输出:Val: '0',Name: ''
我是否在某处造成了溢出?
gates.txt (UTF-8)
123 -> x
struct-string-gates.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILE_NAME "gates.txt"
#define MAX_LINE_LEN 100
#define VAR_NAME_LEN 5
char **readLines(char *fileName) {
FILE *fp = fopen(fileName,"r");
char *buff = malloc(MAX_LINE_LEN * sizeof(char));
// Including the following while loop seems to cause the issue
while (fgets(buff,MAX_LINE_LEN,fp) != NULL) {
// Empty fn
}
char **lines = NULL;
fclose(fp);
free(buff);
return lines;
}
typedef struct Gate Gate;
struct Gate {
char name[VAR_NAME_LEN];
int output;
};
int main() {
char **lines= readLines(FILE_NAME);
Gate *newGate = malloc(sizeof(Gate));
printf("Val: '%d',Name: '%s'\n",newGate->output,newGate->name);
return 0;
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)