The principle and implementation of malloc () and free () under Linux __linux

Source: Internet
Author: User
Tags int size

When learning C language, know the concept of dynamic memory allocation, but also know the use of malloc (), but has not been to understand or seriously learn malloc () the principle of implementation. See today about dynamic memory allocation of information, on the collation of the summary.

In C language, only through malloc () and its derived functions for dynamic application of memory, and the implementation of the fundamental is through the system call implementation (in Linux is through the SBRK () system call implementation), the summary is also based on the Linux system.

Before you explain the implementation of malloc () The idea is to say in the Linux system is how the program in the heap. The management of a program's heap in a Linux system is managed by a block of memory that divides the heap into blocks of memory of varying sizes. How to manage these blocks, such as how to query the size of the block, how to query whether the block is being used by the program, how to know the address of this block. In order to solve the memory block management, we want to design a data structure to manage the memory block, the detailed data structures are as follows:

/** Memory control block data structure for managing all memory blocks
* Is_available: Indicates whether the block is available. 1 indicates available, 0 indicates unavailable
* Size: The block size
**/
struct Mem_control_block {
    int is_available;
    int size;
};
With the management of the memory block data structure, then in the memory of the heap of the organization is also understood, that is, the heap is composed of a lot of memory blocks, so there are the following schematic diagram:

Synthesis of the above knowledge, it is easy to think of malloc () to achieve the general idea. First check whether the memory in the heap is available, if available then the size can meet the demand, if all satisfied with the words directly. When all the blocks of memory in the heap are traversed, the new memory can only be requested from the operating system through a call to the OS, and then the new memory is added to the heap, if there is no block to satisfy the requirement. The idea is simple, the malloc () implementation flowchart looks like this:

After reading the above ideas, it will be easy to think of free () function of the implementation of ideas, as long as the memory management block set to be available. The next time the malloc () function is called, the memory block can be allocated again as an allocation block.

Finally, paste the code implemented by malloc () and free ():

malloc () implementation:

/** Memory control block data structure for managing all memory blocks * Is_available: Indicates whether the block is available.
    1 indicates available, 0 indicates unavailable * Size: The block size **/struct Mem_control_block {int is_available;
int size;

}; /** uses the global variable *managed_memory_start under Linux when implementing malloc: The pointer points to the bottom of the heap, the first memory block in the heap *last_valid_address: the pointer points to the top of the process.
That is, the end address of the last memory block in the heap **/void *managed_memory_start;

void *last_valid_address; The/**malloc () function is dynamically allocated a block of memory that satisfies the requirements of the parameter *numbytes: This parameter indicates how much memory space is to be requested * return value: The function completes returns the memory block head address that satisfies the parameter request, and returns null **/void * If no success is assigned
    malloc (size_t numbytes) {//cursor, pointing to the current memory block void *current_location;
    Saves the memory control structure of the current memory block struct Mem_control_block *CURRENT_LOCATION_MCB;
    The address of the memory block that satisfies the condition is used to return void *memory_location of the function;
    Memory_location = NULL;
    Calculates the actual size of the memory block, which is the size specified by the function parameter + the size of the memory control block numbytes = numbytes + sizeof (struct mem_control_block);

    Using global variables to get the address of the first memory block in the heap current_location = Managed_memory_start;
        Iterate over the memory blocks in the heap, find the appropriate block of memory while (current_location!= last_valid_address) Check to see if the stack is traversed to the top of the heap {//Get the memory control structure of the current memory block CURRENT_LOCATION_MCB = (struct mem_control_block*) current_location; Determine whether the block is available if (current_location_mcb->is_available)/Check whether the block size satisfies the IF (CURRENT_LOCATION_MC B->size >= numbytes) {//satisfied blocks are marked as unavailable Current_location_mcb->is_availa
                ble = 0;
                Get the address of the block, end traversal memory_location = current_location;
            Break
    //Get the next memory block current_location = current_location + current_location_mcb->size;
        = = 1) return null;//application failed, indicating that the system does not have available memory memory_location = last_valid_address;
        last_valid_address = last_valid_address + numbytes;
        CURRENT_LOCATION_MCB = (struct mem_control_block) memory_location;
        current_location_mcb->is_available = 0;
    Current_location_mcb->size = numbytes; //To this has gotten the desired block of memory, now to dois to go over the memory control block to return the first address of the memory block memory_location = memory_location + sizeof (struct mem_control_block);
return memory_location; }

Free () implementation:

The/**free () function is to release the memory block to which the parameter points
*firstbyte: The first address of the memory block to be freed
* return value: null
**/
void free (void *firstbyte)
{
    struct Mem_control_block *MCB;
    Gets the first address of the memory control block of the block
    MCB = firstbyte-sizeof (struct mem_control_block);
    Set the block flag to available
    mcb->is_available = 1;
    return;
}

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.