I'm trying to read a file into an array of strings using getline() and realloc(). I have used very similar code in the past for tokenizing strings and everything worked correctly. I'll consider the sample input file as
1
2
3
4
5
Here's the code:
char** read_input(const char* input_file, char* line){
FILE *fp;
size_t len = 0;
size_t nums = 0;
ssize_t read;
char** res = NULL;
if ((fp = fopen(input_file, "r")) == NULL){
printf("Incorrect file\n", strerror(errno));
exit(EXIT_FAILURE);
}
while ((read = getline(&line, &len, fp)) != -1){
if ((res = realloc(res, sizeof(char*) * ++nums)) == NULL)
exit(EXIT_FAILURE);
char to_strip[sizeof(read) * sizeof(char)];
strcpy(to_strip, line);
if (line[read - 1] == '\n')
to_strip[read - 1] = 0;
else
line[read] = 0;
res[nums - 1] = to_strip;
}
free(line);
if ((res = realloc(res, sizeof(char*) * (nums + 1))) == NULL)
exit(EXIT_FAILURE);
res[nums - 1] = 0;
return res;
}
After the loop, if I print the contents of the array, I get:
5
5
5
5
5
despite the fact that if I call print inside the loop, after each assignment to res, I get the right numbers. This is really stumping me, because I can't see what could be wrong except with realloc, but I thought that realloc preserved array contents. Thanks.