简体   繁体   中英

Custom Memory Allocator in c

I found this link that describes how a custom memory allocator works:

https://github.com/lovelaced/muhalloc/blob/master/mem.c

Why does Mem_Alloc() divide by 4 and increase size to be a multiple of 4?

Here is the description of the function from that link:

/* Function for allocating 'size' bytes. */
/* Returns address of allocated block on success */
/* Returns NULL on failure */
/* Here is what this function should accomplish */
/* - Check for sanity of size - Return NULL when appropriate */
/* - Round up size to a multiple of 4 */
/* - Traverse the list of blocks and allocate the best free block which can accommodate the requested size */
/* -- Also, when allocating a block - split it into two blocks when possible */
/* Tips: Be careful with pointer arithmetic */
void* Mem_Alloc(int size)
    ...

It is for alignment; and is a pretty poor example of how to do it. If you look at the example from K&R's the C Programming Language, it presents the source to an allocator that is portable, effective and easy to understand. C is a subtle language, it is best to learn from reading good programs first.

data alignment, for access memory efficiency

suppose a processor always fetches 4 bytes from memory with an address that must be a multiple of 4. then the value can be read or written with a single memory operation. otherwise, we may need to perform two memory accesses, since the object might be split across two 4-byte memory blocks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM