Search code examples
cscanfrealloc

C program crash after first scanf


This function is causing my program to crash:

void input_data(int** data, int* data_size)
{
    int i;
    char c;

    //input with error handling
    do
    {
        printf("Write, how many integers you want to input: ");
    }
    while (((scanf("%d%c", data_size, &c) != 2 || c != '\n') && clear_stdin()));

    //memory reallocation
    *data = (int *) realloc(*data, *data_size * sizeof(**data));

    printf("\nInput %d integers\n", *data_size);

    for (i = 0; i < *data_size; i++)
    {
        while ((scanf("%d%c", data[i], &c) != 2 || c != '\n') && clear_stdin());
    }
}

In my main() I got

int* numbers = (int *) malloc(1 * sizeof(*numbers));
int input_size;
input_data(&numbers, &input_size);

My program crashes after first integer input, and I believe this is caused by scanf, but I can't realize why. If you need, I can provide full source code of my program.


Solution

  • This isn't doing what you expect:

    scanf("%d%c", data[i], &c)
    

    data[i] is not the address of the i'th element of the array. This expression translates to *(data + i). This expression is actually treating data as an array of int *, but data is a pointer to a int * variable, so this leads to undefined behavior.

    You want to first dereference data, then get the array element. So the expression you want is (*data + i), or equivalently &((*data)[i]).