A linked list is made up of elements where the first element ?must be a pointer. This pointer is used by the linked list library?to form lists of the elements.
int
mmem_alloc(struct mmem *m, unsigned int size)
{/* Check if we have enough memory left for this allocation. */if(avail_memory < size) {return 0;}/* We had enough memory so we add this memory block to the end ofthe list of allocated memory blocks. */list_add(mmemlist, m);/* Set up the pointer so that it points to the first available bytein the memory block. */m->ptr = &memory[MMEM_SIZE - avail_memory];//這句賦值,把那段全局數組和m里面的指針聯系起來了,有了m,就能找到那片內存/* Remember the size of this memory block. */m->size = size;/* Decrease the amount of available memory. */avail_memory -= size;/* Return non-zero to indicate that we were able to allocatememory. */return 1;
}這就是內存分配函數。
void
mmem_free(struct mmem *m)
{struct mmem *n;if(m->next != NULL) {/* Compact the memory after the allocation that is to be removedby moving it downwards. */memmove(m->ptr, m->next->ptr,&memory[MMEM_SIZE - avail_memory] - (char *)m->next->ptr);/* Update all the memory pointers that points to memory that isafter the allocation that is to be removed. */for(n = m->next; n != NULL; n = n->next) {n->ptr = (void *)((char *)n->ptr - m->size);}}avail_memory += m->size;/* Remove the memory block from the list. */list_remove(mmemlist, m);
}內存的釋放。首先看看要釋放的是不是鏈表的最后一個元素,如果是,那么就簡單了,把字節數還回去,再把這塊內存從鏈表上脫離。