Hello C boards,

First time posting here. I am a bit of a noob, but have done my due diligence in trying to understand the behavior. Despite best efforts, I cannot understand or explain the behavior of the below code.

The program takes a text from stdin. The text is a simple stream of data comprised of numbers separated by newlines.

The goal of the program is to store these numbers into an array. The input size is unknown and therefore the program must dynamically allocate additional memory.

When realloc is ran inside main, there is no issue. When realloc is ran from a function call, the program errors with an eventual "realloc(): invalid next size".

To me, a noob, it appears the process is the same regardless of where realloc is called. There must be some fundamental concept I am missing. Could someone help enlighten my lack of understanding?

Again: If I leave the realloc portion uncommented in main and comment out the function call, it works as expected. If I comment out the realloc portion in main and uncomment the function call, it fails.

Below is the code (I will comment out the realloc in main):

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void push_int(int *array, int *counter, int *size, int *value){

    if (*counter >= *size){
        array = realloc(array,  (*size + *counter)*sizeof(int)*2);
        *size = (*size + *counter)*2;
    }
    array[*counter] = *value;


}

int main (int argc, char *argv[]){

    char *line = NULL;
    size_t len = 0;
    ssize_t read;

    char *tok = NULL;
    int number = 0;

    int size = 1;
    int *array = malloc(sizeof(int));

    int counter = 0;

    if (stdin == NULL) {
       exit(EXIT_FAILURE);
    }

    while ((read = getline(&line, &len, stdin)) != -1) {

        tok = strtok(line, "\n");
        number = atoi(tok);

        //if (counter >= size){
        //    array = realloc(array,  (size + counter)*sizeof(int)*2);
        //    size = (size + counter)*2;
        //}

        push_int(array, &counter, &size, &number);        
        
        //array[counter] = number;
        counter ++;
    }
}
I am running gcc version 10.2.0 (GCC) x64 on Linux 5.8.7
I am compiling with: gcc -lm example.c -o example

Thank you