Introduction to malloc and free in C

Source: Internet
Author: User

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:

 1  // Code...  2         char *Ptr = NULL;  3         Ptr = (char *)malloc(100 * sizeof(char));  4         if (NULL == Ptr)  5     {  6         exit (1);  7     }  8         gets(Ptr);  9 10         // code... 11         free(Ptr); 12         Ptr = NULL; 13         // 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.

Okay! This is probably the most basic thing! 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. 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 to pass parameters between functions. 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:

1    // code... 2        void Function(void) 3        { 4         char *p = (char *)malloc(100 * sizeof(char)); 5     }

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 very important! 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, 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 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 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:

Program code:
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. However, there is a problem here. After malloc () applies for a space, a pointer should be returned to point to the second space, that is, the available space! Otherwise, if it points to the management information space, the written content may be inconsistent with the struct type, or the management information will be blocked, then the memory space cannot be released, so an error occurs! (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!

Program code:
// 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 is subtracted from the size of a struct! The following sentence is free-> is_available = 1; I'm wondering! My idea is: Here is_available should be just a tag! The reason is that is_available is "usable ". 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 !! The value of this variable is 1, indicating that it is 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 is a matter of the operating system. From the source code of free (), nothing is released, right? But it does determine the memory content of the management information. Therefore, free () only records some information, and then tells the operating system that the memory can be released. How can I tell the operating system about it, 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 not allowed to release part of it! First, we should understand this. In addition, from the free () source code, 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 address of the management information space. 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 all the friends who participated in this post discussion. Post: http://bbs.bccn.net/thread-81781-1-1.html. I also talked about copyright. If anyone wants to repost this article (if I have the honor), at least mark the words "from bccn c language Forum". I don't need to write my ID! Thank you for your cooperation!

 

Related Article

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.