I keep getting "realloc(): invalid next size" after 3-4 inputs

int main() { // MAX IS DEFINED AS 4
    char **strarr = malloc(MAX * sizeof(char));
    char *input = NULL;
    int counter = 0;
    int mul = 1;
    while (1) {
        input = malloc(sizeof(char) * MAX);

        void *newp = realloc(strarr, mul * MAX * sizeof(char));

        if (fgets(input, MAX, stdin) != NULL) {
            if (newp == NULL) {
                break;
            } else {
                strarr[counter] = input;
                counter++;
                mul++;
            }
        } else {
            break;
        }
    }
}

I'm trying to write a program that reads from stdin and stores what has been written there in a String array. However I keep getting the error "realloc(): Invalid next size" after writing 3 to 4 (depending on how long they are) Strings into stdin. Any help is greatly appreciated.



Read more here: https://stackoverflow.com/questions/64960116/i-keep-getting-realloc-invalid-next-size-after-3-4-inputs

Content Attribution

This content was originally published by Luca.D at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: