Re: Problems with function that returns a pointer to array of strings
- From: Kenneth Brody <kenbrody@xxxxxxxxxxx>
- Date: Tue, 31 Jul 2007 15:15:51 -0400
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>
.
- References:
- Problems with function that returns a pointer to array of strings
- From: paktsardines
- Problems with function that returns a pointer to array of strings
- Prev by Date: How to create a standalone C program?
- Next by Date: Re: error: expected ')' before '*' token -- What is this ?
- Previous by thread: Re: Problems with function that returns a pointer to array of strings
- Next by thread: Declaring variables in "case" blocks?
- Index(es):