Write the memory allocation function malloc by yourself

Source: Internet
Author: User
1. About malloc

I wanted to write this article for a long time. I 've been dragging on and not writing it. I want to write a better version. However, I don't have much time to think about a complete version recently, you only need to write this simple version first. It is said that Microsoft met this question when recruiting interns this year.

Malloc () is a set of standard library functions for Dynamic Storage Management in C language. Its function is to allocate a continuous memory space with a length of size from the dynamic storage area (HEAP) of the memory. The parameter is an unsigned integer, and the returned value is a pointer to the starting address of the allocated continuous storage space. If the memory is insufficient, the function returns NULL if the memory allocation fails.

In Linux, each process can access 3 GB of virtual memory, but during program compilation, it is impossible or unnecessary to allocate such a large space for the program, only a small data segment space is allocated. The dynamically allocated space in the program is allocated from this block. If this space is insufficient, the malloc function family (such as realloc and calloc) will call the sbrk function to move the end Of the data segment, and the sbrk function will map the virtual address space to the memory under the management of the kernel, used by the malloc function. Note that sbrk is a C-library function instead of a system call. System calling usually provides a minimum function, while library functions usually provide more complex functions. For more information about sbrk, see this article: sbrk details. If the memory to be allocated is large, MMAP may be called directly to map memory. Here, by the way, we will mention the difference between malloc and calloc. The memory allocated by malloc will not be cleared, while calloc will reset the memory allocated by it.

2. Hands-on implementation

First, define a struct memory control block for memory allocation as follows:

typedef struct mcb {    int available;    int size;} mcb;

Available indicates whether the memory block is available, 1 indicates available, and 0 indicates unavailable. Size indicates the size of the memory block.When malloc memory segments are used, the size of the MCB struct is added based on the basic size, and the returned allocated memory address needs to skip the MCB struct.

Several global variables are defined as follows. memstart indicates the starting address of the idle memory when the memory is allocated. Lastaddr indicates the last valid memory address, and hasinit indicates whether the memory has been initialized. The initialization function sets memstart to the end position of the current heap, and lastaddr to the end position of the current heap.

void *memStart;void *lastAddr;int hasInit;

Void Init () {lastaddr = sbrk (0); // The tail address of the initialized valid memory is the heap tail location memstart = lastaddr; // initialize the start address of the idle memory; hasinit = 1 ;}

The implementation of the malloc function is as follows:

Void * malloc_mem (INT num) {If (! Hasinit) Init (); void * Current = memstart; // you can specify void * ret = NULL as the start address for querying idle memory; // RET returns the Final allocated memory address num + = sizeof (MCB ); // Add the basic size and memory control block structure to the size of MCB // traverse the allocated memory block to see if there is a suitable size of idle memory block available, // if there is an idle memory block and its size is greater than the size to be allocated, set the occupation status mark, // set the returned memory address ret to the starting address of the idle memory block that is currently traversed and jumps out of the loop. While (current! = Lastaddr) {MCB * pcurrent = current; If (pcurrent-> available & pcurrent-> size> = num) {pcurrent-> available = 0; ret = current; break;} current + = pcurrent-> size; // if no idle block of the proper size is found, traverse the next memory block} If (! RET) {// if no idle block is found, or sbrk (Num) is allocated for the first time; // adjust the size of the heap tail and increase num ret = lastaddr; // set ret to the previous valid address lastaddr + = num; // update the last valid address, and add the allocated memory block size MCB * PCB = ret; PCB-> size = num; PCB-> available = 0;} RET + = sizeof (MCB); // return ret, note that return ret is skipped here for the memory control block size ;}

Since we have written malloc, free is very easy to write,Because the input parameter is the actual starting address of the memory block (skipping the size of the MCB struct), we need to subtract the size of the MCB struct to obtain the memory location of the memory control block McB.And then clear the occupation mark.

 

void free_mem(void *start){    mcb *pmcb = (mcb *)(start - sizeof(mcb));    pmcb->available = 1;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.