0

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;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Levente Wolf
  • 47
  • 1
  • 5

1 Answers1

0

given char **read(FILE *input, char **lines, int *lSize)

what does: realloc(lines, (size *= 2) * sizeof(char *)) do?

Well it changes the sizes of the memory block pointed to by lines, possibly by moving it. That is why it returns a new pointer. Just assigning that new pointer back to lines won't help much (on its own) as that only updates the local variable lines in this function.

But luckily lines is also returned from the function. But its return value is ignored in main so after read returns, the lines in main may be a bogus pointer. do lines = read(file, lines, &lsize) in main as well.

koder
  • 2,038
  • 7
  • 10