Re: Problems with function that returns a pointer to array of strings



paktsardines@xxxxxxxxx wrote:
[...]
char ** read_file(char * filename) {
FILE *fptr;
char *line = malloc(LINE_MAX * sizeof(char));
char **lines = 0;
int linelength = 0;
int i = 0;
[...]
linelength=strlen(line);
line[linelength]='\0';

This is basically a no-op, as line[strlength] is, by definition,
already '\0'.

[...]
lines[i]=line;
[...]
free (line);
return lines;
}

The program currently seems to get through the function okay, but
then seg faults when printing the first line.
[...]

You have pointed every line[i] to the same address, pointed to by
line. (Note that you do not check that line's malloc succeeded.)
You then free() that buffer.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@xxxxxxxxx>


.