Usage of malloc and free Functions

Source: Internet
Author: User

Original article: http://blog.pfan.cn/vfdff/33507.html

Personal Summary

In C language learning, it is especially important to master the knowledge of memory management! Previously, I had little knowledge about the malloc () and free () functions in C, but I only knew how to use them-that is, the malloc function and free function. Of course, I don't know much about these two functions now, but I have a rough understanding of the content in the third part of this article.
Write this article as a summary of knowledge. The reason why this article is named is the word "talking! Hope to help you a little bit!

If it is not too far away (for example, how to manage Virtual Memory and physical memory in the operating system ), I think this article is a comprehensive discussion of malloc () and free (). this article introduces the main content in three parts.

So much nonsense, next, enter the topic ================================="""

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:

// 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, because this can escape

Some compiler checks.

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. An empty record exists in the operating system.
List of 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 delete the node from the idle node linked list and
Allocate the space of the node to the program. That's it!

Speaking of this, I have to insert another small topic. I believe everyone knows what the topic is. What is heap? Speaking of heap, I couldn't help talking about stack! What is stack? The following is an additional part of this topic:

2. What is heap? The heap is the space shared by everyone. It is divided into global heap and local heap. The global heap is all unallocated space, and the local heap is the space allocated by the user. Heap is allocated when the operating system initializes the process. During the running process, you can also request additional heap to the system, but remember to return the heap to the operating system after it is used up. Otherwise, the memory will leak.


STACK: A stack is unique to a thread and stores its running status and Local Automatic variables. The stack is initialized at the beginning of the thread, and the stacks of each thread are independent of each other. Each function has its own stack, which is used in the function
Parameters. The operating system automatically switches the stack when switching the thread, that is, switches the SS/ESP register. Stack space does not need to be explicitly allocated or released in advanced languages.

The above concept description is a standard description, but some of the statements have been deleted by me. I do not know that this makes it unstandard. ^_^.

The following concepts are described:

Stack is automatically assigned and released by the compiler to store function parameter values and local variable values. The operation method is similar to the stack in the data structure.

The heap is usually distributed and released by programmers. If the heap is not released, the program may be recycled by the OS at the end of the program. Note that it is possible, not necessarily. So I want to emphasize it again. Remember to release it!

Note that it is different from the heap in the data structure. The allocation method is similar to the linked list. (I mentioned it a little)

So, for example, if you define a pointer variable in the function, and then apply for a memory in the function to point the pointer to it. In fact, the address of this pointer is on the stack, but the content it points to is on the stack! Note This! So, after applying for a space in a function, for example, the following function:

// Code...

Void function (void)
{
Char * P = (char *) malloc (100 * sizeof (char ));
}

In this example, do not think that the function returns. The destroyed pointer of the stack where the function is located is also destroyed, and the requested memory is also destroyed! This is definitely wrong! Because the requested stack exists in the stack, and the destruction of the stack where the function is located has nothing to do with the stack. So, remember to release it!

3. What is free () released?


This is a simple question. In fact, I want to echo the question of the second largest part! Haha! Free () releases the memory pointed to by the pointer! Note! Memory is released, not a pointer! This is extremely important.
Yes! 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! However, the garbage of the content pointed to by the pointer is undefined.
It is garbage. Therefore, as I have mentioned earlier, after the memory is released, the pointer is directed to null to prevent the pointer from being accidentally referenced. This is very important!

Okay! This "off-Question" is finally finished. Let's simply put it one time. You just need to know about it! The third part is as follows:

Iii. malloc () and free () mechanisms:

This part is new to me today! What's more, it's a matter of attention! Therefore, this Part may have more misunderstandings! Please help us to point out something wrong!

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 pointing to the requested space.

The release can be completed with parameters in free! 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. Let's take a look at the section 7 in "Advanced Programming for UNIX environments:


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 an existing
At the end of the allocation 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. Move the pointer pointing to the allocated block to the backend
It may also rewrite the management information of the block.

The above Section has provided us some information. I think 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, struct is used to record different information of the same object.

Things are justified! Let's take a look at the prototype of this struct:

Struct mem_control_block {

Int is_available; // is this a tag?

Int size; // the actual size of the space.

};

For size, this is the actual space size. In fact, I have a question: Is is_available a tag? Since I read the free () source code, I feel a little confused about this variable (the source code is analyzed below ). Please note that!


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. But here is a question
After applying for a space, malloc () returns a pointer to the second space, that is, the available space! Otherwise, if it points to the management information space, the written content and struct type may not
Consistency, or the management information will be blocked, so the memory space cannot be released, so an error will occur! (I feel like I am talking nonsense here)

Okay! Let's take a look at the free () source code. I analyzed it myself and thought it was much easier than the malloc () source code. I just have a question!

// Code...


Void free (void * PTR)
{

Struct mem_control_block * free;

Free = PTR-sizeof (struct mem_control_block );

Free-> is_available = 1;

Return;
}


Let's take a look at the second sentence of the function. This sentence is very important and key. In fact, this sentence is to reverse the pointer pointing to the available space and let it point to the space that manages information, because the value here is subtracted from the size of a struct.
Small! The following sentence is free-> is_available =
1. I'm wondering! My idea is: Here is_available should be just a tag! Because from the perspective of the variable name, is_available
The translation is "yes ". Don't mention me! I think the variable name can reflect the role of a variable, especially the rigorous code. This is the source code, so I think it is absolutely rigorous !! Value of this variable
Yes. 1 indicates a usable space! I just thought about it. What will happen if I change it to 0 or other values ?! But one thing I can be sure of is that release will never proceed so smoothly!
Because this is a mark!


Of course, there may still be some questions here. why can it be released in this way ?? I have this question just now. Later, I thought that releasing the operating system would be a matter of fact, so let's look at the free () source code,
Nothing is released, right? But it does determine the memory content of the management information. Therefore, free () only records some information and tells the operating system that the memory can be released.
I don't know how to tell the operating system, but I think this is beyond the scope of my article.


So, I had a wrong idea that the pointer to the memory can be released no matter where it is moved to the memory! However, this is a big mistake! Release is a part that cannot be released
Of! First, we should understand this. In addition, from the source code of free (), PTR can only point to the first address of the available space. Otherwise, after subtracting the size of the struct, it must not point to the first place of the management information space.
Address. Therefore, make sure that the Pointer Points to the first address of the available space! Believe it? You can write a program and move the pointer to the available space!

Finally, you may think of the source code of malloc () to see how malloc () allocates space. This involves a lot of other knowledge! If you are interested, you can download the source by yourself.
Code to see.

4. Others:

Here is the discussion about malloc () and free () in C! After three hours, I felt a little tired! Hope to help you! You are welcome to point out something wrong! Last
Thank you for participating in this post to discuss all friends, post: http://www.bc-cn.net/bbs/dispbbs.asp? Boardid = 5 & id = 81781 & page = 1. I also talked about copyright. If anyone wants to repost this article (if I have the honor), at least mark the words "from the BC-CN C language Forum, I don't need to write my ID! Thank you for your cooperation!

V. References: (write the title only)

-- Advanced Programming in UNIX environment

-- Computer composition principle

-- High quality C/C ++ programming guide

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.