Home > Mobile >  Memory leak in C (malloc)
Memory leak in C (malloc)

Time:07-18

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 alocated 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 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?

CodePudding user response:

Will free(s); clear the space in heap memory?

free(s); will release the memory reservation. The memory is generally made available for other use. You can free memory anywhere in the source code. It does not need to be in the same routine that allocated it. malloc and free are intended for dynamic memory allocation, meaning it is controlled by the running program, not by the compiler or any compile-time constraints such as location in the source code.

free(s); generally does not clear the space. The C standard does not require an implementation to clear the memory. Common behaviors include leaving the memory unchanged until it is reallocated, using the memory to help manage the pool of available memory, and, as a debugging feature when requested, “scribbling” patterns of data into the memory to make it more likely that any incorrect use of the memory will cause noticeable symptoms in the problem (rather than letting a bug go undetected).

CodePudding user response:

It's ok ! You can free memory outside of the function that creates it, but that's considered bad practice. If the consumer of the 'add' function can't get the source code, it can't know you're using malloc. To solve this problem, you have to pass it as an argument and avoid using malloc in the 'add' function:

int *add ( int*a, int*b, int* res)
{
    *res = (*a) (*b);
    return res;
}

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