See Csapp Write memory allocator

Source: Internet
Author: User
Tags define get
<span id="Label3"></p>Goal: implement a placement strategy for the first time, and then close the strategy to a memory allocator that is based on an implicit idle list immediately.<p><p><br></p></p><p><p>Here we use the memory system model provided by the MEMLIB.C package, which allows us to run the allocator without interfering with the existing malloc package, that is, the malloc function is Encapsulated.</p></p><p><p>Memlib.h</p></p><p><p></p></p><pre name="code" class="cpp"><pre name="code" class="cpp">void Mem_init (void); void *mem_sbrk (int incr);</pre></pre><br><br><p><p></p></p><p><p>Memlib.c: (the malloc function is Encapsulated)</p></p><p><p></p></p><pre name="code" class="cpp"><pre name="code" class="cpp">#include <stdio.h> #include <stdlib.h> #include "csapp.h" #define MAX_HEAP (1 <<) static char *mem_ heap; /* Points to first byte of heap */static char *mem_brk; /* Points to last byte of heap plus 1 */static char *mem_max_addr; /* Max Legal heap addr plus 1*/void mem_init (void) { mem_heap = (char *) Malloc (max_heap); MEM_BRK = (char *) mem_heap; mem_max_addr = (char *) (mem_heap + max_heap); }/* * Mem_sbrk-simple model of the SBRK Function. Extends the heap * by incr bytes and returns the start address of the new Area. In * This model, The heap cannot is Shrunk. */void *mem_sbrk (int incr) { char *old_brk = mem_brk; If ((incr < 0) | | ((MEM_BRK + Incr) > Mem_max_addr)) {errno = enomem;fprintf (stderr, "error:mem_sbrk failed. Ran out of memory...\n "); return (void *)-1; } MEM_BRK + = incr; return (void *) old_brk;</pre></pre><p><p></p></p><p><p>Mm.h</p></p><p><p></p></p><pre name="code" class="cpp"><pre name="code" class="cpp">/************************************************************************* > File name:mm.h > Author:connan_d > Mail: [email protected] > Created time:2015 May 07 Thursday 10:40 49 sec > defines the interface for the memory allocator * /int mm_init ();//initialize void *mm_malloc (size_ T size);//allocate memory void Mm_free (void *bp);//reclaim memory</pre></pre><br>Mm.c<p><p></p></p><p><p></p></p><pre name="code" class="cpp">/************************************************************************* > File name:mm.c > Author:connan_ d > Mail: [email protected] > Created time:2015 May 07 Thursday 10:50 51 seconds ********************************** /#include <stdio.h> #include "mm.h" #include "memlib.h" static void * Extend_heap (size_t Words);//expand The free space of the heap, return to the original heap top address (mem_brk), fail back nullstatic void *coalesce (void *bp);//and bp points to the front and rear blocks of the block, Returns the block pointer to the static void *find_fit (size_t Size);//find The first space larger than the size of the free block, return its address, when not found, return nullstatic void place (void *bp, size_t Asize);//split Find_fit returned block, create block Structure//macro definition # wsize 4#define dsize 8#define CHUNKSIZE (1<<12)//size of each expansion heap # define MAX ( x, Y) ((x) > (y)? (x): (y)) #define PACK (size, Alloc) (size) | (alloc)) Combine block size and flag bits into a word # define GET (p) (* (unsigned int *) (p))//return P point to the word # define PUT (p, val) (* (unsigned int *) (p) = (val))// Press the value into the word # define Get_size (p) (get (p) & ~0x7)//returns The High 29 bits of the head or tail, that is, the Block's size # define GET_ALLOC (p) (GET (p) & 0x1)//returns the flag bit #defIne HDRP (bp) ((char *) bp-wsize)//the Head of the return block # define FTRP (bp) ((char *) bp + get_size (bp)-dsize)//return Block's Trailing # define NEXT_BLKP (bp) ( (char *) (bp) + get_size ((char *) bp-wsize))//current when Block's next piece # define PREV_BLKP (bp) ((char *) bp-get_size ((char *) Bp-dsize)//return but previous block of S tatic void *heap_listp;//points to the first block (prologue block)//interface int mm_init (void)//initialized, successfully returned 0, failed to return {mem_init (); if (HEAP_LISTP = mem_sbrk (4 * Wsize)) = = (void *)-1) return-1; PUT (heap_listp, 0); Put (HEAP_LISTP + wsize, pack (8, 1));//preamble block head put (HEAP_LISTP + 2*wsize, pack (8, 1));//preamble block tail put (HEAP_LISTP + 3*wsize, pack (0, 1));//end block HEAP_LISTP + = 2*wsize;if (extend_heap (chunksize/wsize) = = NULL) Return-1;return 0;} void Mm_free (void *bp)//release bp pointer to block memory {size_t size = get_size (HDRP (bp)); PUT (HDRP (bp), PACK (size, 0)); PUT (ftrp (bp), PACK (size, 0)), coalesce (bp), block}void *mm_malloc (size_t size)///allocate size byte size block, return pointer to block {size_t asize ;//adjusted sizesize_t extendsize;void *bp;if (size = = 0) return null;if (size < Dsize) asize = 2 * dsize;elseasize = Dsize * (size + (dsize) + (DSIZE-1))/dsize); if ((bp = Find_fit (asize)) = NULL) {place (bp, asize); return bp;} Extendsize = MAX (asize, CHUNKSIZE), If ((bp = extend_heap (extendsize/wsize)) = = NULL) return null;place (bp, asize); return bp;} The tool function defines the static void *extend_heap (size_t words)//expansion heap Free space, Returns the original heap top address (mem_brk), and fails back Null{char *bp;size_t size;size = (words % 2)? (words + 1) * wsize:words * wsize;//keep double word alignment if ((long) (bp = mem_sbrk (size)) = =-1) return NULL; PUT (HDRP (bp), PACK (size, 0)); PUT (ftrp (bp), PACK (size, 0)); PUT (HDRP (next_blkp (bp)), PACK (0, 1)); return (void *) bp;} The static void *coalesce (void *bp)//and bp points to the front and back blocks of the block, and the block pointer {size_t prev_alloc = Get_alloc (HDRP (PREV_BLKP (bp)) is returned and closed; Whether the previous block is assigned size_t next_alloc = get_alloc (HDRP (next_blkp (bp)));//whether The next piece is assigned size_t size;if (prev_alloc && Next_alloc) { Return bp;} else if (prev_alloc &&!next_alloc) {size + = get_size (HDRP (next_blkp (bp))); PUT (HDRP (bp), PACK (size, 0)); PUT (FTRP (bp), PACK (size,0));} else if (!prev_alloc && next_alloc) {size + = get_size (HDRP (prev_blkp (bp))); PUT(FTRP (bp), PACK (size, 0)); PUT (HDRP (prev_blkp (bp)), PACK (size, 0)); bp = Prev_blkp (bp);} Else{size + = get_size (HDRP (prev_blkp (bp)) + get_size (ftrp (next_blkp (bp))); PUT (HDRP (prev_blkp (bp)), PACK (size, 0)); PUT (ftrp (next_blkp (bp)), PACK (size, 0)); bp = Prev_blkp (bp);} Return bp;} static void *find_fit (size_t Size)//find The first space larger than the size of the free block, return its address, when not found, return null{void *bp;for (bp = heap_listp; Get_size (bp) > 0; bp = Next_blkp (bp)) {if (get_size (HDRP (bp)) >= SIZE && get_alloc (HDRP (bp))! = 1)//returns The first free block with unallocated space greater than size return bp;} Return NULL;} static void Place (void *bp, size_t asize)//split Find_fit returned block, creating block structure {size_t bsize = get_size (HDRP (bp)); if (bsize-asize) ; 2*dsize)//minimum block is 16 bytes, split block {PUT (HDRP (bp), PACK (asize, 1)); PUT (ftrp (bp), PACK (asize, 1)); bp = Next_blkp (bp); PUT (HDRP (bp), PACK (bsize-asize, 0)); PUT (ftrp (bp), PACK (bsize-asize, 0));} Else//without splitting {PUT (HDRP (bp), PACK (asize, 1)); PUT (ftrp (bp), PACK (asize, 1));}}</pre><br>Mmtest.c<p><p></p></p><p><p></p></p><pre name="code" class="cpp"><pre name="code" class="cpp">/************************************************************************* > File name:mmtest.c > Author:connan_d > Mail: [email protected] > Created time:2015 May 07 Thursday 14:23 30 Seconds *********************                                     /#include <stdio.h> #include "mm.h" int main () {mem_init (); Initialize model Mm_init (); Initialize the indexer int *a = Mm_malloc (sizeof (int));//test int*a = 1;char *b = Mm_malloc (sizeof (char));//test char*b = ' Z ';d ouble *c = Mm_ma Lloc (sizeof (double)); Test double*c = 2.0;printf ("a =%d\nb =%c\nc =%f\n", *a, *b, *c);}</pre></pre><br>The Csapp.h header file is required to compile the link: gcc-o mmtest mmtest.c mm.c memlib.c-lpthread<p><p></p></p><p><p>Results:</p></p><p><p><br></p></p><p><p>See Csapp Write memory allocator</p></p></span>
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.