malloc implementation?

前端 未结 3 1773
心在旅途
心在旅途 2020-11-29 23:58

I\'m trying to implement malloc and free for C, and I am not sure how to reuse memory. I currently have a struct that looks like this:

3条回答
  •  悲&欢浪女
    2020-11-30 00:40

    You don't want to set the size field of the dictionary entry to zero -- you will need that information for re-use. Instead, set freed=1 only when the block is freed.

    You cannot coalesce adjacent blocks because there may have been intervening calls to sbrk(), so that makes this easier. You just need a for loop which searches for a large enough freed block:

    typedef struct _mem_dictionary
    {
        void *addr;
        size_t size;
        int freed;
    } mem_dictionary;
    
    
    void *malloc(size_t size)
    {
         void *return_ptr = NULL;
         int i;
    
         if (dictionary == NULL) {
             dictionary = sbrk(1024 * sizeof(mem_dictionary));
             memset(dictionary, 0, 1024 * sizeof(mem_dictionary));
         }
    
         for (i = 0; i < dictionary_ct; i++)
             if (dictionary[i].size >= size
              && dictionary[i].freed)
         {
             dictionary[i].freed = 0;
             return dictionary[i].addr;
         }
    
         return_ptr = sbrk(size);
    
         dictionary[dictionary_ct].addr = return_ptr;
         dictionary[dictionary_ct].size = size;
         dictionary[dictionary_ct].freed = 0;
         dictionary_ct++;
    
         return return_ptr;
    }
    
    void free(void *ptr)
    {
        int i;
    
        if (!dictionary)
            return;
    
        for (i = 0; i < dictionary_ct; i++ )
        {
            if (dictionary[i].addr == ptr)
            {
                dictionary[i].freed = 1;
                return;
            }
        }
    }
    

    This is not a great malloc() implementation. In fact, most malloc/free implementations will allocate a small header for each block returned by malloc. The header might start at the address eight (8) bytes less than the returned pointer, for example. In those bytes you can store a pointer to the mem_dictionary entry owning the block. This avoids the O(N) operation in free. You can avoid the O(N) in malloc() by implementing a priority queue of freed blocks. Consider using a binomial heap, with block size as the index.

提交回复
热议问题