Detailed description of malloc and free Functions

Source: Internet
Author: User

This article describes the content of the malloc and free functions.

In C, memory management is very important. The following describes the two functions:

 

  1. Basic Concepts and usage of malloc () and free:

1. function prototype and description:

Void * malloc (long NumBytes): This function allocates NumBytes bytes and returns a pointer to this memory. If the allocation fails, a NULL pointer is returned ).

There are many reasons for allocation failure, such as insufficient space.

Void free (void * FirstByte): This function returns the space previously allocated with malloc to the program or the operating system, that is, this memory is released, so that it is free again.

 

2. Function usage:

In fact, these two functions are not very difficult to use, that is, after malloc () is used up, I think it is enough to give it free (). For example:

Program code:
// Code...
Char * Ptr = NULL;
Ptr = (char *) malloc (100 * sizeof (char ));
If (NULL = Ptr)
{
Exit (1 );
}
Gets (Ptr );

// Code...
Free (Ptr );
Ptr = NULL;
// Code...

That's it! Of course, the specific situation should be analyzed and solved. For example, if you have defined a pointer, applied for a piece of memory in a function, and passed it to the pointer through the function return, then the release of the memory should be left to other functions.

 

3. Notes for using functions:

A. After applying for memory space, you must check whether the allocation is successful.

B. When you do not need to use the requested memory, remember to release it. After the memory is released, point the pointer to this memory to NULL to prevent the program from using it accidentally.

C. These two functions should be paired. If the application is not released, the memory is leaked. If the application is released without reason, nothing is done. Only one release is allowed. If two or more releases are performed

An error occurs (with the exception of releasing the NULL pointer, releasing the NULL pointer does not actually do anything, so it is no problem to release the NULL pointer many times ).

D. Although the type of the malloc () function is (void *), any type of pointer can be converted to (void *), but it is best to force type conversion before, this can avoid some compiler checks.

Now go to the second part:

 

  II. Where does malloc () Get the memory space:

1. Where does malloc () obtain the memory space? The answer is to get space from the heap. That is to say, the pointer returned by the function points to a piece of memory in the heap. The operating system has a linked list that records idle memory addresses. When the operating system receives a program application, it traverses the linked list and searches for the first heap node with a larger space than the requested space, then, the node is deleted from the idle node linked list and the space of the node is allocated to the program. About heap knowledge, you can query data structure knowledge or query a previous post C/C ++ heap, stack, and static data area [review]. I will not mention it here.

 

2. After using malloc () to allocate memory space, remember to release the memory space. Otherwise, the memory will leak.

3. What is free () released?

Free () releases the memory pointed to by the pointer! Note! Memory is released, not a pointer! The pointer is not released, and the pointer still points to the original bucket. A pointer is a variable and is destroyed only when the program ends. After the memory space is released, the pointer to this space still exists! But now the Pointer Points to the content of the garbage, is undefined, so said garbage. Therefore, after the memory is released, the pointer is directed to NULL to prevent the pointer from being accidentally referenced.

 

  Iii. malloc () and free () mechanisms:

In fact, a closer look at the free () function prototype may also find that it seems amazing. The free () function is very simple and has only one parameter, you only need to pass the pointer to the requested space to the parameter in free () to complete the release! Here we need to track the malloc () application. The actual memory occupied during application is larger than that applied. Because the excess space is used to record the management information of the memory.

In most implementations, the allocated storage space is slightly larger than the required one. The additional space is used to record management information-the length of the allocated block, pointer to the next allocated block, and so on. This means that if you have written the end of an allocated area, the management information of the last part will be rewritten. This type of error is catastrophic, but it is difficult to find it because it will not be exposed soon. Moving the pointer pointing to the allocated block backward may also rewrite the management information of the block.

The space applied for by malloc () is actually divided into two different types of space. One is the space used to record management information, and the other is the available space. What is used to record management information is actually a struct. In C, structures are often used to record information! Let's take a look at the prototype of this struct:

Program code:
Struct mem_control_block {
Int is_available; // It is generally the first address of an available space, but an English word indicates whether the space is available.
Int size; // the actual size of the space.
};

 

Therefore, free () is to release the space requested by malloc () based on the structure information! The size of the two members of the struct should be the size of the operating system. Let's take a look at the source code of free ().

// Code...

Void free (void * ptr)
{
Struct mem_control_block * free;
Free = ptr-sizeof (struct mem_control_block );
Free-> is_available = 1;
Return;
}

 

For the malloc source code, you can find it online if you are interested!

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.