• Advertisement

Archived

This topic is now archived and is closed to further replies.

Memory Management

This topic is 5906 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi all, Does anyone have any docs on the way that malloc allocates memory? Such as how it determines where there is enough free memory? Cheers,

Share this post


Link to post
Share on other sites
Advertisement
no docs but if malloc returns a NULL pointer then there is not enough memory!

henry

Share this post


Link to post
Share on other sites
The way malloc works is system and compiler dependant, but the basic idea is this:

0) The memory for an application is allocated continuously. That is, an application that owns the memory at 0x1000 and 0x2000, say, owns all the memory in between.

1) There is a function (brk on UNIX systems) that requests additional memory from the operating system: this memory is appended to the end of the application''s memory (if there isn''t enough room, the program may be moved about.)

2) The malloc system keeps a list of the chunks of memory that are free, and those chunks that are allocated. When new memory is requested from the OS, it is placed on the free list.

3) When the program requests memory using malloc, the library first checks to see if there is a chunk large enough on the free list. If there is, enough memory is taken out of the chunk to cover the reuired amount and placed on the allocated list - the remaining part of the chunk is left on the free list.

4) If there isn''t enough space on the free list, the library will ''defragement'' the free list: chunks that contigious in memory will be combined into one chunk. Then, it''ll check the free list again.

5) If there still isn''t enough space, the library will ask the operating system for some more memory.

6) When memory is freed, its chunk is placed on the free list. At this point, fragmentation can occur because memory might not be freed in the same order in which is is allocated. Since it is time-consuming to defragment, this is only done when it''s absolutely necessary.

There are issues of alignment and various optimisations depending upon the machine, operating system and/or compiler, but the basic framework is the same everywhere.

Abolish Software Patents! | freepatents | lpf

Share this post


Link to post
Share on other sites
Thanks for all the info!

By any chance is there somewhere where I can''t get some info on the GCC implementation? I need to check out a few things such as if it''s multi-thread safe...


Thanks again,

Share this post


Link to post
Share on other sites
The malloc that comes with the GNU C library, which is probably what you''ve got if you''re using gcc, is described here.

Abolish Software Patents! | freepatents | lpf

Share this post


Link to post
Share on other sites

  • Advertisement