Home > other >  Logical error while using realloc() function
Logical error while using realloc() function

Time:09-27

I am using dynamic memory allocation in C for a simple problem that I am trying to solve. It involves taking user input for the elements of 2 arrays. I was thinking that I will initialise the array to a large size and use realloc to reduce the size once the input has been completed. ?below is the code for same:

void arrayop()
{
    int val, i=0;
    int *arr1 = (int*) calloc(100,sizeof(int));
    int *arr2 = (int*) calloc(100,sizeof(int));
    printf("Enter first array:(-1 to stop)\n");
    while(val!=-1)
    {
        if(val != -1)
        {
            scanf("%d",&val);
            *(arr1   i) = val;
            i  ;
        }
    }
    //printf("\t%d\n",i);

    arr1 = (int*)realloc(arr1,(i));
    //printf("\t%d\n",(sizeof(arr1)));
    for(int j=0;j<i;j  )
    {
        printf("%d ",*(arr1   j));
    }
    printf("\n");
}

However, realloc() is somehow overwriting already entered elements and filling them with garbage value. Can anyone give me any insight as to why this is happening, or where I am wrong? Output showing the array with garbage value

CodePudding user response:

realloc expects the allocation size, but you're telling it how many ints you want. When you call it like this:

arr1 = (int*)realloc(arr1,(i));

i holds the number of ints that you want to allocate space for, but the actual size needed for the allocation is i * sizeof(int), so to fix it you need:

arr1 = realloc(arr1, sizeof(int) * i);

Or, even better:

arr1 = realloc(arr1, sizeof(*arr1) * i);

The second variant will work even if you change the type of arr1 from int * to, say, short *.

You may also want to check the pointer returned by realloc and make sure the allocation succeeded. Note that if realloc fails, arr1 won't be freed and you'll end up leaking it. A better approach is:

int *temp = realloc(arr1, sizeof(*arr1) * i);
if (temp == NULL)
{
    fprintf(stderr, "realloc failed\n");
    free(arr1);
    return;
}
arr1 = temp;

While we're at it, don't cast the result of malloc, calloc, or realloc. See Do I cast the result of malloc? .

  • Related