hlx98007
hlx98007

Reputation: 241

Array of string in a struct pointer

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?

Upvotes: 0

Views: 65

Answers (2)

Kaizhe Huang
Kaizhe Huang

Reputation: 1006

You need to allocate memory for each line before you can copy data to it:

  record->line[i] = malloc(MAX_STR_SIZE+1);    // allocate memory first.
  fgets((*record).lines[i], MAX_STR_SIZE, in); // <-- Segment fault here

Upvotes: 2

John Bode
John Bode

Reputation: 123598

You're missing an allocation step; for each passwd->lines[i], you need to do another allocation:

// Allocate space for array of pointers
passwd->lines = malloc( sizeof *passwd->lines * max_number_of_strings );
for ( size_t i = 0; i < max_number_of_strings; i++ )
{
  // Allocate space for each string
  passwd->lines[i] = malloc( sizeof *passwd->lines[i] * max_string_length );
}

Upvotes: 2

Related Questions