I have a following struct:
strcut records
{
char **lines;
int count;
}
There is a function get_pwent() which the concerning code is like this:
struct records *passwd = malloc(sizeof(strcut records));
passwd->lines = malloc(sizeof(char *) * MAX_STR_SIZE);
With a few malloc error checking (passwd is not null, passwd->lines is not null) it's passed down to my 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
}
The file is /etc/passwd and I want to read in the first line of this file and store that into the struct records lines[i] position.
I also tried this:
fgets(record->lines[i], ...) //which also gets a seg fault.
in GDB, under parse_file() scope:
(gdb) p record
$1 = {struct records *} 0x602250
How can I fix this error?
recordis not NULL,record->linesis not NULL, andrecord->lines[i]is a string allocated withMAX_STR_SIZE?passwd(recordinparse_filescope) is notNULL, and so does itslines.fgetswill considerably increase chances for success. Right now you allocate the array of pointers, but the value of each pointer is indeterminate. You allocate no space for the actual string read. With that, you invoke undefined behavior, and (fortunately) crash in the process.