I want to implement dynamically growing array in C. I read the words from a file to a char** array and when the array is full grow its size by 2. But when I reallocate the memory, the first two elements of the array is lost. I tried with lines = realloc() but it's crashing. What am I doing wrong?
test.txt:
test1
test2
test3
test4
test5
test6
test7
test8
test9 (no end of line)
my output:
─
đ%
test3
test4
test5
test6
test7
test9
Code:
#include <stdio.h>
#include <malloc.h>
int size = 8;
char **read(FILE *input, char **lines, int *lSize) {
for (int i = 0; !feof(input); i++) {
*lSize += 1;
if (*lSize > size) {
realloc(lines, (size *= 2) * sizeof(char *));
for (int j = (*lSize) - 1; j < size; j++) {
lines[j] = (char *) malloc(1024 * sizeof(char));
}
}
fscanf(input, "%s", lines[i]);
}
return lines;
}
int main(){
FILE *file = fopen("test.txt", "r");
if (file == NULL) {
return -1;
}
char **lines = malloc(size * sizeof(char *));
for (int i = 0; i < size; ++i) {
lines[i] = malloc(1024 * sizeof(char));
}
int lsize = 0;
read(file, lines, &lsize);
printf("lSize:%d\n", lsize);
printf("size:%d\n", size);
for (int i = 0; i < lsize; ++i) {
printf("%s\n", lines[i]);
}
for (int i = 0; i < size; ++i) {
free(lines[i]);
}
free(lines);
return 0;
}