Find the answer to your Linux question:
Results 1 to 3 of 3
Hi all, When I am using malloc and free, how the compiler knows how much memory to be freed. --Cheers Madhu...
  1. #1
    Just Joined!
    Join Date
    May 2009
    Posts
    21

    how free() works in C

    Hi all,

    When I am using malloc and free, how the compiler knows how much memory to be freed.

    --Cheers
    Madhu

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    The compiler keeps a list of this, but ultimately it is the kernel that has to keep track of how much memory was reserved for the process, and where.

    So if your application crashes, the kernel can still properly free all the memory.
    Linux Memory Management Overview
    Debian GNU/Linux -- You know you want it.

  3. #3
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Generally, malloc() and free() use a pool that is allocated by the OS and provided to the application by the sbrk() function. They manage this memory as a linked list, allocating memory in chunks. So, if you allocate a single byte, you actually will get a chunk of memory up to a couple kb in size. This is why some C++ string classes have their own allocators for small strings to avoid the memory overhead associated with malloc'd memory. Anyway, it is fairly complicated to write a set of malloc/free functions that are efficient in both time and memory usage. I have written a number of allocators in the past, and all I can say to someone who is not inclined to "reinvent the wheel", is that the standard functions work, and work pretty well. Don't worry about what that guy behind the curtain is doing!
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...