Пример #1
0
void *mm_malloc(size_t size) {
	if (size > 0) {
    	if (!start) {
    		start = request_space(size);
    		if (!start) {
    			return NULL;
    		}
    		start->free = 0;
			last = start;
    		return start+1;
    	} else {
    		struct metadata *block;
    		block = find_block(size);
    		if (!block) {
    			block = request_space(size);
    			if (!block) {
    				return NULL;
    			}	
    		} else {
    			if ((block->size - size) >= (sizeof(struct metadata))) {
    				split(block, size); 
    			}
    		}
    		block->free = 0;
    		void *ptr = (void *)block + sizeof(struct metadata);
    		memset(ptr, 0, size);
    		return ptr;
    	}
    }
    return NULL;
}
Пример #2
0
char *
malloc(size_t size) {
  struct malloc_chunk *block;
 
  if (size <= 0) {
    return NULL;
  }

  if (!heap_start) { // First call.
    block = request_space(NULL, size);
    if (!block) {
      return NULL;
    }
    heap_start = (char*) block;
  } else {
    struct malloc_chunk *last = (struct malloc_chunk*) heap_start;
    
    block = find_free_block(&last, size);
    
    if (!block) { // Failed to find free block.
      block = request_space(last, size);
      if (!block) {
        return NULL;
      }
    } else {      
	  // Found a block we can re-use
		/*
      if ((block->size - size) > (31+MALLOC_CHUNK_SIZE)) {
		 
		  // if the block we are re-using is considerably larger (32 bytes)
		  // than what we request, then split it.
		  int old_size = block->size;
		  block->size = size;
		  // save next ptr
		  struct malloc_chunk *next = (struct malloc_chunk*) block->fd;
		  char* p = (char*) block;
		  p = p + (MALLOC_CHUNK_SIZE + size);
		  
		  block->fd = (struct malloc_chunk*) p;
		  
		  // point to next free byte
		  //(char*) block->fd = (char*) block + size + MALLOC_CHUNK_SIZE;
		  
		  // create a new block header for the remainder of the block
		  struct malloc_chunk *split = (struct malloc_chunk*) block->fd;
		  
		  split->size = old_size - MALLOC_CHUNK_SIZE - size;
		  split->is_free = 1;
		  split->fd = next;
		  
		  
		  
	  }
	  */
      block->is_free = 0;
    }
  }

  return(block+1);
}
Пример #3
0
void *myallocate_self(int size)
{	
	struct block_meta *block;
	struct block_meta *last = global_base;
	
	
	
	if (!global_base) 
	{ // First call.
	   
	   	block = request_space(NULL, size);
	    if (!block) 
	    {
	      return NULL;
	    }
	    global_base = block;
    } 
  else {
    block = find_free_block(&last, size);
    if (!block) 
    { // Failed to find free block.
      block = request_space(last, size);
      if (!block) 
      {
        return NULL;
      }
    } 
    else 
    {      // Found free block
      // TODO: consider splitting block here.
      block->free = 0;
    }
  }
  return block;
}