--malloc functions for C/C + + base

Source: Internet
Author: User

Prototype: extern void *malloc (unsigned int num_bytes);

Usage: #include <malloc.h>

or #include <stdlib.h>

Function: Allocate a block of memory with a length of num_bytes bytes

Note: Returns a pointer to the allocated memory if the assignment succeeds, or null if the null pointer is returned.

When memory is no longer in use, you should use the free () function to release the memory block.

The syntax for malloc is: pointer name = (data type *) malloc (length), (data type *) represents a pointer.

[Edit the working mechanism of the]MALLOC () function of this section

The substance of the malloc function now, it has a so-called idle list that connects the available chunks of memory to a long listing. When the malloc function is invoked, it looks for a block of memory that is large enough to meet the user's request in the join table. The memory block is then split in half (the size of the piece is equal to the size of the user request, and the other is the remaining byte). Next, the memory assigned to the user is passed to the user, and the remaining piece, if any, is returned to the connection table. When the free function is invoked, it connects the memory blocks freed by the user to the idle chain. In the end, the free chain will be cut into a lot of small memory fragments, if the user requests a large memory fragment, then the idle chain may not be able to meet the user requirements of the fragment. As a result, the MALLOC function requests a delay and begins to rummage through the free chain to check each memory fragment, organize them, and merge the adjacent small free blocks into larger chunks of memory.

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.