/* * malloc */ void *malloc (size_t size) { checkheap(1); // Let's make sure the heap is ok! unsigned int awords; //Adjusted block size unsigned int ewords; //Amount to extend heap if no matching uint32_t *block; uint32_t * heap_lastp = last_block(); if (VERBOSE) printf("Malloc %d bytes\n", (int)size); /* Ignore 0 requests */ if (size == 0) return NULL; /* Adjust size to include alignment and convert to multipes of 4 bytes */ if (size <= DSIZE) awords = 2; else awords = (((size) + (DSIZE-1)) & ~0x7) / WSIZE; /* Search the free list for a fit */ if ((block = find_fit(awords)) != NULL) { place(block, awords); //printf("3\n"); return block_mem(block); } /* No fit found. Get more memory and place the block */ if (awords > CHUNKSIZE) ewords = awords; else if (0) ewords = awords; else ewords = CHUNKSIZE; if (block_free(heap_lastp)) { ENSURES(block_size(heap_lastp) < ewords); ewords = ewords - block_size(heap_lastp) + 2; //ewords += 2; //printf("1\n"); } else { ewords += 2; // ask for 2 more for the header and footer //printf("2\n"); } if ((block = extend_heap(ewords)) == NULL) return NULL; place(block, awords); return block_mem(block); }
//Find the first fit static void *find_first_fit(size_t size) { uint32_t *ptr = (uint32_t *)heap_ptr + 2; unsigned int bsize = block_size(ptr); while(bsize > 0) { if((size <= bsize) && !block_free(ptr)) return (void *)block_mem(ptr); ptr = block_next(ptr); bsize = block_size(ptr); } return NULL; }
// Returns 0 if no errors were found, otherwise returns the error int mm_checkheap(int verbose) { void* current; //void* prev; size_t size; for(int i = 0; i < NUM_FREE_LISTS; i++){ current = free_lists[i]; //prev = NULL; while(current != NULL){ if(!in_heap(current)){ if(verbose) printf("HEAP ERROR: block not in heap\n"); printf("CURRENT: %p\n", current); return 1; } size = block_size(current); if(size > MAX_SIZE){ if(verbose) printf("HEAP ERROR: invalid block size\n"); return 1; } /* if(block_prev(current) != prev){ if(verbose) printf("HEAP ERROR: invalid prev pointer\n"); return 1; } */ if(!block_free(current)){ if(verbose) printf("HEAP ERROR: block in list not marked free\n"); return 1; } if(!aligned(current) || !aligned(block_mem(current))){ if(verbose) printf("HEAP ERROR: block not aligned\n"); return 1; } //prev = current; current = block_next(current); } } return 0; }
/* * malloc */ void *malloc (size_t size) { void* p; int index; if(heap_start == 0) mm_init(); checkheap(1); // Let's make sure the heap is ok! if(size == 0) return NULL; size += 8 - size%8; size += (HEADER_SIZE + FOOTER_SIZE); if(size > MAX_SIZE) return NULL; index = get_free_list_index(size); p = find_free_block(index, size); if(p == NULL) return NULL; p = block_mem(p); checkheap(1); return p; }