我有以下结构:
strcut records
{
char **lines;
int count;
}
有一个函数get_pwent()
,相关代码如下:
struct records *passwd = malloc(sizeof(strcut records));
passwd->lines = malloc(sizeof(char *) * MAX_STR_SIZE);
通过一些 malloc 错误检查(passwd
不为空,passwd->lines
不为空)它被传递到我的 parse_file()
:
parse_file(struct records *record, FILE * in)
{
int i = 0;
... // a while loop
fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here
i++;
... // end while
}
该文件是/etc/passwd,我想读取该文件的第一行并将其存储到 struct records lines[i] 位置。
我也试过这个:
fgets(record->lines[i], ...) //which also gets a seg fault.
在 GDB 中,在 parse_file()
范围内:
(gdb) p record
$1 = {struct records *} 0x602250
我该如何修复这个错误?
最佳答案
你需要为每一行分配内存,然后才能将数据复制到它:
record->line[i] = malloc(MAX_STR_SIZE+1); // allocate memory first.
fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here
关于c - 结构指针中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26389573/