cmallocheap-memory

Memory leak in C (malloc)


To learn heap memory, I used the following code. I used malloc inside a called function (fn1), and for some I reason, I decided not to free the memory inside the called function (fn1). I passed the address of the random allocated memory as return to the calling function (fn2). So after using the data from the heap memory in called function (fn2), can I free the malloc'ed memory outside the called function (fn1)?

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

int *add(int *a, int *b)
{
    int *c = (int *)malloc(sizeof(int));
    *c = (*a) + (*b);
    return c;
}

void main()
{
    int a = 2, b = 3;
    int *s = add(&a, &b);
    printf("The sum is: %d\n", *s);
    free(s);
}

In the above code, I'm returning the dynamically allocated value c as function return and storing it in s. Will free(s) clear the space in heap memory?


Solution

  • It's OK! You can free memory outside of the function that allocates it, but that's considered bad practice. If the users of the add function cannot get the source code, they cannot know you're using malloc. To solve this problem, you should pass it as an argument and avoid using malloc in the add function:

    #include <stdio.h>
    #include <stdlib.h>
    
    void add(int *a, int *b, int *res)
    {
        *res = (*a) + (*b);
    }
      
    void main()
    {
        int a = 2, b = 3;
        int *c = (int *)malloc(sizeof(int));
        add(&a, &b, c);
        printf("The sum is: %d\n", *c);
        free(c);
    }