I have two related questions hence I am asking them in this single thread.
Q1) How can I confirm if my OS is clearing un-“free”‘ed memory (allocated using malloc) automatically when a program terminates? I am using Ubuntu 11.04, 32-bit with gcc-4.5.2
As per a tutorial page by Steven Summit here, “Freeing unused memory (malloc’ed) is a good idea, but it’s not mandatory. When your program exits, any memory which it has allocated but not freed should be automatically released. If your computer were to somehow “lose” memory just because your program forgot to free it, that would indicate a problem or deficiency in your operating system.“
Q2) Suppose, foo.c mallocs a B-bytes memory. Later on, foo.c frees this B-bytes memory locations and returns it to the OS. Now my question is, can those PARTICULAR B-bytes of memory locations be re-allocated to foo.c (by the OS) in the current instance OR those B-bytes can’t be allocated to foo.c untill its current instance terminates ?
EDIT : I would recommend everyone who reads my question to read the answer to a similar question here and here. Both answers explain the interaction and working of malloc() and free() in good detail without using very esoteric terms. To understand the DIFFERENCE between memory-management tools used by kernel (e.g. brk(), mmap()) and those used by the C-compiler (e.g. malloc(), free()), this is a MUST READ.
When a process ends either thru a terminating signal, e.g.
SIGSEGV, or thru the _exit(2) system call (which happens to be called also when returning frommain), all the process resources are released by the kernel. In particular, the process address space, including heap memory (allocated with mmap(2) (or perhapssbrk(2)) syscall (used bymalloclibrary function) is released.Of course, the
freelibrary function either (often) makes the freed memory zone reusable by further future calls tomallocor (occasionally, for large memory zones) release some big memory chunk to the kernel using e.g.munmap(2)system call.To know more about the memory map of process 1234, read sequentially the
/proc/1234/mapspseudo-file (or/proc/self/mapsfrom inside the process). The /proc file system is the preferred way to query the kernel about processes. (there is also/proc/self/statmand/proc/self/smapsand many other interesting things).The detailed behavior of
freeandmallocis implementation dependent. You should viewmallocas a way to get heap memory, andfreeas a way to say that a previouslymalloc-ed zone is useless, and the system (i.e. standard C library + kernel) can do whatever it wants with it.Use valgrind to hunt memory leak bugs. You could also consider using Boehm’s conservative garbage collector, i.e. use
GC_mallocinstead ofmallocand don’t bother about freeing manually memory.