我正在尝试读取文本文件并将数据存储在struct数组中,但是我遇到了分段错误。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char name[24];
unsigned short value;
}Flags;
int ReadData(char * filename, Flags* retv){
//First getting the number of lines, this helps to allocate the memory for the struct
char line[255];
int linenr = 0;
char* token;
FILE* myfile = fopen(filename, "r");
while(!feof(myfile))
{
char ch = fgetc(myfile);
if(ch == '\n')
{
linenr++;
}
}
retv = malloc(linenr * sizeof(Flags));
linenr = 0;
// Bring the file pointer to the beginning
rewind(myfile);
// Read data line by line
while (fgets(line, sizeof(line), myfile)) {
token = strtok(line, "=");
if (token != NULL){
strcpy(retv[linenr].name, token);
// Getting the value
token = strtok(NULL, "=");
if (token != NULL)
retv[linenr].value = atoi(token);
else
retv[linenr].value = 0;
// Debugging
#ifdef DEBUG
printf("i: %d\n", linenr);
printf("Name: %s\n", retv[linenr].name);
printf("Value: %d\n", retv[linenr].value);
#endif
linenr ++;
}
}
fclose(myfile);
return linenr;
}
int main(int argc, char const *argv[])
{
Flags * values;
int linenr = 0;
int i;
// Read the data
linenr = ReadData("test.txt", values);
// Some debugging
printf("Line number: %d\n", linenr);
for (i = 0; i < linenr; i++)
{
printf("i: %d\n", i);
printf("Name: %s\n", values[i].name);
printf("Value: %d\n", values[i].value);
}
free(values);
return 0;
}
输出是:
i: 0
Name: fa_flag
Value: 0
i: 1
Name: s2s_flag
Value: 12
i: 2
Name: torque_flag
Value: 1
i: 3
Name: torque_flag2
Value: 1
i: 4
Name: torque_flag3
Value: 1
Line number: 5
i: 0
Name: (null)
Segmentation fault (core dumped)
我无法弄清楚我在哪里弄错了。
答案 0 :(得分:3)
问题在于:
int ReadData(char * filename, Flags* retv){
....
retv = malloc(linenr * sizeof(Flags));
正确分配内存,但main
中的指针未更新。
Flags * values;
....
linenr = ReadData("test.txt", values);
将其更改为:
int ReadData(char * filename, Flags** retv){
....
*retv = malloc(linenr * sizeof(Flags));
和
Flags * values;
....
linenr = ReadData("test.txt", &values);