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 .
Thank you
|
If the object lives to the end of the program, then you don't need to call |
|||||||||
|
As pointed out in this question, for the particular case of freeing memory immediately before terminating the program, 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 |
||||
|
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). |
|||
|