cmallocrealloccalloc

realloc function dynamic array size more than stated


I am trying to add memory of my dynamic array using realloc. But in my code, realloc is added extra memory to the array. Suppose initially I want to create array of 5 items than I want to add 3 more items, so the total length of the array should be 8. But it is showing more than the allocated length, why? I have attached the output also.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n, i, added_data;
    int *data;

    printf("Enter the total number of elements: ");
    scanf("%d", &n);

    
    data = (int *)calloc(n, sizeof(int));
    if (data == NULL)
    {
        printf("Error!!! memory not allocated.");
        exit(0);
    }

    
    for (i = 0; i < n; i++)
    {
        printf("Enter number %d: ", i + 1);
        scanf("%d", data + i);
    }

    printf("Enter number of elements to add: ");
    scanf("%d", &added_data);

    if(added_data > 0)
    {
        data = realloc(data, added_data * sizeof(int));

        for (i=0; i < added_data; i++)
        {
            //n++;
            printf("Enter number %d: ", i + 1);
            scanf("%d", data + n);
            n++;
        }
    }

    int new_length = n + added_data;
    printf("\nnew length of array: %d", new_length);
    printf("\n");

    for(i=0;i<new_length;i++)
    {
        printf("%d\n", data[i]);
    }

    printf("\n");

    free(data);

    return 0;
}

Output::

Enter the total number of elements: 5
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number of elements to add: 3
Enter number 1: 55
Enter number 2: 99
Enter number 3: 88

new length of array: 11
1
2
3
4
5
55
99
88
10053856
0
10027344

Solution

  • The allocated array isn't more than stated. You just calculated the size wrong.

    You initially read in the value 5 for n and read in 5 values. When you then read in 3 for added_values and subsequently read 3 more values, you increment n for each item you read in.

    So after reading in a total of 8 items, n is now equal to 8. Adding 3 to that gives you 11.

    You also have a bigger problem here:

    data = realloc(data, added_data * sizeof(int));
    

    This isn't increasing the size of the memory to hold 3 additional int values, it's setting the total size to 3 int values. So writing the additional elements to the array triggers undefined behavior.

    You need to fix this reallocation to account for the total size, and you should use a separate variable to keep track of the current index you're writing to.

    if(added_data > 0)
    {
        data = realloc(data, (n + added_data) * sizeof(int));
    
        int current = n;
        for (i=0; i < added_data; i++)
        {
            printf("Enter number %d: ", i + 1);
            scanf("%d", data + current);
            current++;
        }
    }