Search code examples
carraysmallocrealloc

malloc and realloc array giving unexpected output


When input is '1 2 3 4 5 6 7 8 9 10 11' Expected output should be the same as input. Yet the output is '1 2 3 4 5 6 7 8 9 10 -1850774484' . Only happens when there are more than 10 integers being inputted. Where did I go wrong with my realloc line

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

#define INITIAL_SIZE 10

int
main(int argc, char **argv){
    int i = 0, num, size = 0, n = INITIAL_SIZE;
    int *A;

    A = malloc(n * sizeof(int));

    if(A == NULL){
        printf("OUT OF MEMORY\n");
        exit(EXIT_FAILURE);
    }

    while(scanf("%d",&num) == 1 && getchar()!='\n'){
        A[i] = num;
        i++;
        size++;
        if (size >= n){
            n = n * 2;
            A = realloc(A,n * sizeof(int));
        }
    }

    printf("Int Array: ");
    for (i = 0; i <= size; i++){
        printf("%d ", A[i]);
    }
    printf("\n");

    return 0;
}

Solution

  • There is nothing wrong with the realloc. You are printing an extra uninitialized index in the last loop. Fix it by changing

    for (i = 0; i <= size; i++)
    

    to

    for (i = 0; i < size; i++)
    

    The only problem with the realloc is that you don't check if it was successful just like you did for the malloc. Another problem is that you don't free the allocated memory.