c - Does every malloc call have to be freed -
from understand because malloc dynamically assigns mem , need free mem can used again.
- what happens if return char* created using malloc (i.e. how supposed free that)
- if leave pointer , exit application freed.(i cant find definite answer on , yes , no).
the caller has free (or arrange freed). means functions create , return resources need document how should freed.
most oses free memory when program exits, part of definition of "process". c standard doesn't care happens, it's beyond scope of program. not oses have full process abstraction, desktop-style oses do.
the main reasons free before are:
- if free memory possible, long time before process exit, program uses less memory total.
- if don't free it, , later want change program routine within program, perhaps called many times, require many times memory before (memory leak).
- there debugging tools identify memory leaks, warning memory still allocated when program exits. these don't if there's lot of deliberately-leaked junk wade through.
- if don't free , hit problems, it's harder go later , find memory needs freeing, right in first place.
- there many cases need free memory (to prevent huge memory use in long-running programs), default strategy must clean pretty anyway.
the vaguely plausible reasons not free are:
- less code.
- if have squillions of blocks free individually, before program exit, might faster let os drop whole process.
- stuff created on demand , stored in globals might quite difficult clean safely, if don't know it's used. think of kind of cache that's populated go along, might have mru rules limit how memory occupies, it's not unlimited leak. ok, 1 bad thing (unrestricted globals) causing bad thing (unfreed memory), it's worth knowing reason why might see unfreed blocks in existing code, , can't go in , fix them.
the reasons freeing outweigh reasons against.
Comments
Post a Comment