0

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?

2 Answers2

1

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).

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
  • Thank you for your answer. But I have a doubt. I did not understand the idea of releasing the memory. From what I know, if I did not free the malloc memory, calling the function several times leaves a trail of garbage values in the Heap memory. The program will consume more memory while running. I'm learning C program in the scope of embeded programming. So I have to consider the limitations of memory management. Can you please explain in detail, thank you. – Karthikeyan Krishnanandan Jul 17 '22 at 16:19
  • @KarthikeyanKrishnanandan: Every call to `malloc` should have exactly one corresponding call to `free`, once the memory is no longer needed. Otherwise, you have a [memory leak](https://en.wikipedia.org/wiki/Memory_leak), and if you have several such memory leaks, they may accumulate over time, increasing the memory usage of your program. – Andreas Wenzel Jul 17 '22 at 17:02
0

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);
}
Abdo21
  • 498
  • 4
  • 14
  • 2
    I disagree that it is generally considered "bad practice" for a function to allocate memory without freeing it later, as long as this does not create a memory leak but rather a transfer of ownership of the memory to a different function. For example, the standard library function [`strdup`](https://en.cppreference.com/w/c/string/byte/strdup) does this by design. Therefore, I see nothing wrong with this, as long as the behavor is clearly documented. However, you are right that in the case of the `add` function, it does not make much sense. – Andreas Wenzel Jul 17 '22 at 16:34
  • Well, since heap allocation is the only way to extend the lifetime of structures beyond the return of a function, avoiding it because of 'bad practice' would make many things imposs....'very, very difficult'. Suppose you create a window instance in a GUI message-handler, how are you going to ensure that the instance remains valid when the handler returns to the message handling loop? You need to queue/signal a pointer to a large buffer to another thread - how do you ensure that the buffer remains valid when the receiving thread eventually gets the pointer? – Martin James Jul 17 '22 at 22:11
  • 'bad practice' doesn't mean you shouldn't use it at all, it means you should avoid it as much as possible, but if you have a good reason, do it, you need to know when to break the rule. – Abdo21 Jul 18 '22 at 23:56