Is it necessary to call free function every time we use malloc in C. I am asking this because I have seen many times that it is not called .
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.Sign up to join this community
If the object lives to the end of the program, then you don't need to call
free, but I would hold that it is still good practice to do so. The reason here is that, at the end of your code's execution, all of the memory will be
free'd anyway, so there's no need to do so explicitly. Otherwise, yes; use
As pointed out in this question, for the particular case of freeing memory immediately before terminating the program,
free is a waste of time if your program runs on pretty much any modern operating system. You'll be making the allocator do the work of tracking down the memory and marking it as unused, despite the fact that the OS can free the memory in one fell swoop. As Raymond Chen points out, if the amount of memory to be freed at program exit is large, the time wasted can be significant.
However, this behavior is still OS-dependent. With respect to the language, it is always wrong to not free memory. More importantly, tools like lint or Valgrind will report this as an error, and if you get used to ignoring their errors you defeat the purpose of using them. So I'd treat the practice of not freeing at program exit as an optimization, and you shouldn't optimize prematurely.
If we're not talking about program exit, failing to
free is most definitely a bug. No one would intentionally do that if their goal is to write a program that doesn't leak memory.
Each call to malloc allocates memory on the heap and returns a pointer to it. If you do not call free on the returned pointer, the memory is not freed (so you get a memory leak).
In most trivial cases it is not really necessary to call free (i.e. the application will probably run fine without it), but most people (rightly) consider not freeing the memory a bug.
There are also cases when you allocate memory with malloc and leave it in a static or global variable, relying on the operating system to release this memory when the application finishes running. Normally you shouldn't do this. If you have need of a memory block to remain allocated as long as a library has work to do, consider adding a Finalize/Close/Finish/Uninitialize API to your library that de-allocates this memory (such an API should be called as the last call of your program into your library API).
TLDR: While in most cases it may not be strictly necessary, omitting free-ing the memory is a bug and you (probably) should avoid it (i.e. ensure you always call free for malloc-ed memory).