[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: execve - what happens to dynamically allocated memory?

On Wed, 31 Oct 2001 21:36, H. S. Teoh wrote:
> > I'm wondering what happens to dynamically allocated memory. For
> > example, if you have a code snippet such as:
> [snip]
> The dynamically allocated memory is deallocated. Mostly because the
> allocation of memory via malloc() is done strictly within the C library,
> and the only time it actually uses system resources is when it calls
> sbrk() to grab more heap memory when it runs out.

For libc6 in it's default mode of operation...  Other malloc libraries may do 
different things.  For example Electric Fence allocates memory with mmap() 

Compile the following program both with and without the "-lefence" option and 
notice the different memory addresses you get.  Also run it through strace 
and see how the different malloc() libraries perform.

#include <stdlib.h>
#include <stdio.h>

int main()
  int i;
  for(i = 0; i < 10; i++)
    printf("%X\n", malloc(8192));
  return 0;

NB  Your programs are not forced to use libc for malloc() and friends.  There 
are other malloc libraries available for real use (Electric Fence is a 
special case of a debugging tool), some of which will use mmap().  Also for 
extra fun there are situations where a program can use more than one malloc 
library (this makes it very important to call the version of free() that 
matches the version of malloc()).

> So the memory is only "allocated" from the point of view of the C library;
> as far as the system is concerned, the program data segment is just
> occupying a single stretch of addresses (including any as-yet unallocated

Except for memory allocated by mmap(), memory mapped files, etc.

> dynamic memory) -- no different from another program that doesn't use
> dynamically allocated memory. When sbrk() is called, the system just adds
> more addresses to the segment; no problem there.
> When execve() is called, the system removes everything in this data
> segment and replaces it with the data segment from the new process.
> Now, it would be a different story if the program started allocating
> *system* resources, such as shared memory and semaphores... I'll leave
> that for better-clued developers to answer :-)

Posix shared memory can either remain after process exit (or crash) or can be 
set to be removed after exit.  The OpenWall patch (in package 
kernel-patch-2.2-openwall by RVDM) for 2.2.x kernels has an option to clean 
these up (which may break some programs).

http://www.coker.com.au/bonnie++/     Bonnie++ hard drive benchmark
http://www.coker.com.au/postal/       Postal SMTP/POP benchmark
http://www.coker.com.au/projects.html Projects I am working on
http://www.coker.com.au/~russell/     My home page

Reply to: