0

I work with memory allocation and suppose the allocation failed. Do I have to free all the memory in the program before I exit ? Is this really necessary ? Can exit() be enough ?

And if I do need to free all the memory in the program, suppose I have large program with a lot of information in it. How can I manage to do that?

michael kova
  • 105
  • 2
  • 8

3 Answers3

0

In most operating systems all memory owned by process is freed upon exit of that process.

tumdum
  • 1,981
  • 14
  • 19
0

Do I have to free all the memory in the program before I exit ? Is this really necessary ? Can exit() be enough ?

Only you need to free() the memory which was successfully allocated.

free() takes pointer which was returned by malloc() realloc() and calloc() so you need to pass this pointer to free() if this is NULL then no operation will be done by free() so no need to worry about failed allocation.

Yes exit() is enough because when you exit all the allocated memory is freed automatically in many operating systems.

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

Well, that depends.

If you want to continue after certain allocation has been failed, at the end [or after the memory allocation is not used anymore, whichever is earlier], you've to free() the successfully allocated memory.

OTOH, if you're taking the hard-way, making the application to exit straightaway after an allocation failure, then you can avoid the free-ing part.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261