Search code examples
cpointersruntime-errorrealloc

re-alloc Invalid Pointer runtime error


Code below merges 2 sorted arrays A and B of size n1 and n2 respectively.
Merged output needs to be stored in A.

(No need to go through entire code)
Doubt: While re-allocating A, I am getting a run-time error. Why?

int* temp = (int*)realloc(A,sizeof(int)*(n1+n2));
if(temp != NULL) A = temp;

Code for reference:

void putinend(int* num,int m,int n){
    int i,j;
    for(i=m-1,j=m+n-1;i>=0;i--)
        num[j--] = num[i]; 
}
void merge(int* A, int n1, int* B, int n2) {
    int* temp = (int*)realloc(A,sizeof(int)*(n1+n2));
    if(temp != NULL) A = temp;
    putinend(A,n1,n2);
    int s1=n2,s2=0,i=0;
    while(s1 < n1+n2 && s2 < n2){
        if(A[s1] <= B[s2]) 
            A[i++] = A[s1++];
        else 
            A[i++] = B[s2++];
    }
    while(s1 < n1+n2)
        A[i++] = A[s1++];
    while(s2 < n2)
        A[i++] = B[s2++];
    printf("\n");
    for(i=0;i<10;i++){
        printf("%d ",A[i]);
    }
}
int main() {
    int *A = (int*)malloc(sizeof(int)*8);
    int *B = (int*)malloc(sizeof(int)*2);
    A[0]=1; A[1]=3; A[2] = 5; A[3] = 7; A[4] = 9; A[5] = 11; A[6] = 13; A[7] = 15;
    B[0]=-2; B[1]=2;
    int i;
    merge(A,8,B,2);
    printf("\n");
    for(i=0;i<10;i++){
        printf("%d ",A[i]);
    }
    return 0;
}

Edit: I incorporated corrections given below. But Output returned is

-2 1 2 3 5 7 9 11 13 15 
0 3 5 7 9 11 13 15 0 17 

Why does A change just before returning from merge() and just after returning from merge() in main()?


Solution

  • You call realloc() on an array allocated on the stack. The *alloc() functions work with the heap, though.

    From man realloc:

    Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().

    Replace

    int A[8];
    

    with something like

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

    Don't forget to call free() if you need to.