Search code examples
carraysrealloc

Realloc in C random int


I have a problem with reallocating memory of dynamically allocated array. So what i am trying to do is:

typedef struct {
    int s;
    int l;
    int* arr;
    bool orient;
}DAC;
...
int main()
{
DAC heap = {
        4, 0, (int*)malloc(4 * sizeof(int))
    };
    char c = 0;
    int n = 0;
    while (1)
    {
        scanf("%c", &c);
        switch (c)
        {
        case '+':
            if (heap.s == heap.l)
            {
                heap.s *= 2;
                heap.arr = (int*)realloc(heap.arr, heap.s);
            }
            scanf("%d\n", &(heap.arr[heap.l]));
            heap.l++;
            break;
        case 'p':
            for (int i = 0; i < heap.l; i++)
                printf("%d ", heap.arr[i]);
            printf("\n");
            break;
        }
    }

}

As long as my whole structure works for n<5 (i start with array of size '4'), weird things happens when this block is executed:

if (heap.s==heap.l)
{
heap.s*=2;
heap.arr=(int*)realloc(heap.arr,heap.s);
}

What is the reason im getting wrong output at index [2] of my array? I know i could do it with mallocs, just wondering as i think it is weird case

Whole input/output:

+ 1
+ 2
+ 3
+ 4
p
1 2 3 4
+ 5
p
1 2 -33686019 4 5

Solution

  • You start correct when you initialize heap:

    DAC heap = {
            4, 0, (int*)malloc(4 * sizeof(int))
        };
    

    But when you actually want to increase the size, you forget to adjust to the size of integers. Instead of increasing the size to fit for 8 int values, you only get 8 bytes instead.

    As Felix G reminded in a comment, you should never directly assign to the same pointer. If realloc returns NULL you have no more access to the old address.

    Use this instead:

                if (heap.s == heap.l)
                {
                    heap.s *= 2;
                    void *tmp = realloc(heap.arr, heap.s * sizeof(int));
                    if (tmp != NULL) {
                        heap.arr = tmp;
                    } else {
                        // handle error...
                    }
                }