Search code examples
cdynamic-memory-allocationfree

How use free() function in this case? using malloc() and realloc()


Can you tell me where i have to put the free() function for the array "arr" in this code? I tried to put free(arr) before the last printf() but in this way my output is wrong. I'm trying also to check if the memory allocated is free.

int *boh(int *arr,int n);

int main() {
    int a,i,n;
    int *arr;
    int *b;
    int size = 6;

    arr = (int*) malloc(size* sizeof(int));

    for (i= 0; i<6; i++){
        printf("Give me a number: \n");
        scanf("%d",&a);
        
        if(i != 5){
            arr[i] = a;
        }
        else{
            n = a;
        }
    }


    b = boh(arr,n);


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

    return 0;
}


int *boh(int *arr,int n){
    int *a;
    int i;
    int b;
    b = arr[4];
    a = (int*) realloc(arr,n*sizeof(int)+sizeof(arr));
    
    for(i=5; i<5+n; i++){
        b += b;
        arr[i] = b;
    }
    
    return arr;
}

Solution

  • Can you tell me where i have to put the free() function for the array "arr" in this code?

    There is no appropriate place for your main program to free() pointer arr because function boh() reallocates the block to which it points. Thereafter, the pointer you have responsibilty to free is the one returned by realloc(), not the original one. The original pointer must be considered invalid. The two may in practice have the same value, but often they do not.

    For that reason, your function boh also must not attempt to write through the original value of arr after the reallocation, as it does when it evaluates arr[i] = b.

    These corrections are required:

    • check the return value of every malloc() and realloc() (and calloc()) call. These functions return a null pointer on failure, in which event you need to accommodate that in some way, such as cleanly terminating the program.

    • After verifying that realloc()'s return value is not null, your function boh must use that value instead of the original value of arr. A fairly easy way to do that would be simply to assign it to arr before the for loop:

           arr = a;
      

      In this case, that will also cause the function to return the new pointer value, which is the one you have responsibility to free.

    • In the main program, free b after you're done using it (that is, just before the return).

    I'm trying also to check if the memory allocated is free.

    C does not provide any way to test the allocation status of a pointer. The programmer needs to track that themself. However, you could consider running your program under control of an external leak-checking program such as Valgrind.