On the malloc and free in C

Source: Internet
Author: User

In the C language learning, the memory management this part of the knowledge mastery is particularly important! There was little understanding of the malloc () and free () two functions in C before, just know how to use them-that is, malloc and free all OK. Of course, there is not much of the experience of these two functions, but for the third part of this article has a turning point of understanding, so

Write down this article as a summary of the knowledge. This article is named in a "talking about" the word, that is the meaning of it! Hope to have a little help to everyone!

If it's not too far away (such as how virtual memory and physical memory are managed in the operating system, etc.), I feel that this article should be a more comprehensive discussion of malloc () and free (). This article introduces the main content in three parts.




The basic concepts and basic usage of malloc () and free ():

1. Function prototype and Description:

void *malloc (Long numbytes): The function allocates numbytes bytes and returns a pointer to the memory. If the allocation fails, a null pointer is returned (NULL).

There should be a number of reasons for the allocation failure, such as a lack of space.

void *firstbyte: This function returns the space previously allocated by malloc back to the program or the operating system, which frees up the memory and lets it regain its freedom.

2, the use of functions:

In fact, these two functions are not very difficult to use, that is, malloc () after feeling enough to dump it to give it to free (), for a simple example:

Code ...

char *ptr = NULL;

PTR = (char *) malloc (* sizeof (char));

if (NULL = = Ptr)
{
Exit (1);
}

Gets (PTR);

Code ...

Free (PTR);

PTR = NULL;

Code ...

That's it! Of course, the specific situation to be specific analysis and specific solutions. For example, if you define a pointer, request a piece of memory in a function and pass it to the pointer through a function return, then perhaps the work of freeing this piece of memory should be left to other functions.

3. Some places to note about function use:

A. After you have applied for memory space, you must check whether the assignment was successful.

B, when you do not need to use the requested memory, remember to release; After release, the pointer to this memory should be pointed to NULL, prevent the program accidentally used it.

C, the two functions should be paired. If it is not released after the application is a memory leak, if it is released for no reason, nothing is done. Release only once, if released two times and more than two times will

An error occurred (releasing the null pointer exception, releasing the null pointer is actually tantamount to doing nothing, so releasing the null pointer frees up the number of times without a problem).

D, although the type of the malloc () function is (void *), any type of pointer can be converted to (void *), but it is better to make a forced type conversion before, because it can avoid a

Some compiler checks.

All right! The most basic things probably say so! Now go to Part two:


Second, where does malloc () come from? Memory space:

1. Where did malloc () Get the memory space? The answer is to get space from the heap. That is, the pointer returned by the function is a piece of memory pointing to the heap. The operating system has a linked list that records the free memory address. When the operating system receives a request for a program, it iterates through the list and then finds the heap node where the first space is larger than the requested space, and then deletes the node from the list of idle nodes and assigns the space of that node to the program. That's it!

Speaking of this, we have to insert a small topic, I believe we also know what the topic. What is a heap? Speaking of heaps, but also can't help talking about the stack! What is a stack? Here's another small section specifically and simply to say this digression:

2, what is a heap: The heap is a common space for everyone, divided into the global heap and local heap. The global heap is all unallocated space, and the local heap is the space allocated by the user. The heap is allocated when the operating system initializes the process, and it can be added to the system during the run, but remember to return it to the operating system, or memory leaks.

What is a stack: the stack is unique to the thread, saving its running state and local automatic variables. The stack is initialized at the beginning of the thread, and the stacks are independent of each other. Each function has its own stack, which is used to pass arguments between functions. The operating system automatically switches the stack when switching threads, or switches the SS/ESP register. Stack space does not require explicit allocation and deallocation in high-level languages.

The above concept description is the standard description, but there are individual statements that I delete, do not know because of this and become not standard ^_^.

Through the above description of the concept, you can know:

The stack is automatically allocated by the compiler, storing the function's parameter value, the value of the local variable, and so on. Operations are similar to stacks in data structures.

The heap is typically released by the programmer and, if not released, may be reclaimed by the OS at the end of the program. Note that this is possible, not necessarily. So I want to emphasize once again, remember to release!

Note that it is not the same as the heap in the data structure, but the distribution is similar to the linked list. (I mentioned a little bit above)


So, for example, if you define a pointer variable on a function, then you apply a piece of memory in the function to have the pointer point to it. In fact, the address of this pointer is on the stack, but what it points to is on the heap! Pay attention to this point! So, think again, after applying space in a function, for example, the following function:

Code ...

void Function (void)
{
Char *p = (char *) malloc (* sizeof (char));
}

For this example, do not assume that the function is returned, the stack is destroyed by the destruction of the pointer is also destroyed, the application of memory is the same as destroyed! This is absolutely wrong! Because the requested memory is on the heap, and the stack where the function resides is destroyed, it has absolutely nothing to do with the heap. So, still the sentence: Remember to release!

3. What did free () release?

This problem is relatively simple, in fact, I want to and the second most of the topic to echo it! Ha ha! Free () releases the memory that the pointer points to! Attention! The memory is released, not the pointer! This is very, very important! A pointer is a variable that is destroyed only at the end of the program. Once the memory space is freed, the pointer to the space is still there! Just now the pointer points to the content of the garbage, is undefined, so it is rubbish. So, as I've said earlier, after releasing the memory, point the pointer to null, preventing the pointer from being accidentally followed by a dereference. It's very important.

All right! This "digression" finally finished. Just say it once, know a little about it! Here's the third part:

Third, the mechanism of malloc () and free ():

I have a new understanding of this part today! And it's a transformational understanding! So, this part may have some more recognition errors! The wrong place please help point out!

In fact, a closer look at the function prototype of free () may also be found to be magical, the free () function is very simple, with only one parameter, as long as the pointer to the application space is passed

Give free () the parameters to complete the release work! This is to track down the application of malloc (). The amount of memory used in the application is larger than the application. Because the excess space is used to record management information about this memory. Let's take a look at the seventh chapter in advanced Programming for the UNIX environment:

Most implementations allocate more storage space than required, and additional space is used to record management information-the length of the allocated block, the pointer to the next allocation block, and so on. This means that if the end of a allocated area is written, the latter piece of management information is overwritten. This type of error is catastrophic, but it is difficult to spot because the error is not immediately exposed. Moving a pointer to an allocation block backwards may also overwrite the management information for this block.

This passage has given us some information. The space for malloc () application I think it's just a space of two different natures. One is the space to record management information, and the other is the available space. What is used to record management information is actually a struct. In the C language, the use of structs to record different information about the same object is

That's the thing! Here's a look at the prototype of this structure:

struct Mem_control_block {

int is_available; Is this a marker?

int size; This is the size of the actual space

};

For size, this is the actual space size. I actually have a question here, is is_available a mark? Because I looked at the source code of free () I feel a little puzzled about this variable (the source is analyzed below). Here also please point out!

So, free () is the space to release the malloc () application based on the structure's information! And the size of the two members of the struct I think it should be the operating system. But here's a problem, malloc () to return a pointer after the space should be pointing to the second space, that is, free space! Otherwise, if you point to the management information space, the type of content and struct may be inconsistent, or the management information will be masked out, it will not be able to free up memory space, so there will be an error! (I feel like I'm talking nonsense here.)

All right! Let's take a look at the source code of free (), I analyzed it myself, and felt that it was much easier than the source of malloc (). Just have a question, the following point!

Code ...


void free (void *ptr)
{

struct Mem_control_block *free;

free = ptr-sizeof (struct mem_control_block);

free->is_available = 1;

Return
}

Look at the second sentence of the function, this sentence is very important and key. In fact, this is a pointer to the free space back, let it point to the management of the information of the space, because here is the value of a structure minus the size of a body! The following sentence free->is_available = 1; I'm a little puzzled! My idea is: here is_available should be just a mark! Because from the name of this variable, is_available translates "can be used". Don't Call me dirt! I think the variable name can reflect the role of a variable, especially the rigorous code. This is the source code, so I feel absolutely rigorous!! The value of this variable is 1, which indicates that space is available! Just here I thought, if I changed it to 0 or something else, what would happen?! But one thing I can be sure of is that the release will never go so smoothly! Because this is a marker!

Of course, there may be people here who have doubts, why is it possible to release it?? I have the same question just now. Then I thought, the release is the operating system, then the free () This source code to see that nothing is released, right? But it really is the content of that piece of memory that determines the management information. So, free () just record some information, and then tell the operating system that block of memory can be released, specifically how to tell the operating system I am not clear, but I think this is beyond the scope of my article discussion.

Well, I was wrong to think that a pointer to that memory would release that memory wherever it moved to that memory! But that's a big mistake! Release is not part of the release! First of all, this should be understood. Also, from the source of free (), PTR can only point to the first address of the available space, otherwise, minus the struct size must not point to the first address of the management information space. So make sure the pointer points to the first address of the free space! Don't you believe me? You can write a program and then move the pointer to the free space to see if the program will collapse!

Finally, you might think of the source of malloc () to see how malloc () is allocating space, which involves a lot of other knowledge! Interested friends can go to download the source by themselves
Code to see.


Iv. about other:

The discussion of malloc () and free () in C is written here! Wrote three head, feel a bit tired! Hope to help everyone! There is no place to welcome everyone to point out! At last
, thank you for participating in this post discussion of all friends, Posts:http://bbs.bccn.net/thread-81781-1-1.html。 Also talk about copyright issues, if you want to reprint this article (if I have this honor), at least please mark "from BCCN C language forum" These words, my ID can not write! Thank you for your cooperation!


V. References: (write the title only)

--Advanced programming for the Environment of Unix

--the principle of computer composition

--High quality C + + Programming Guide

On the malloc and free in C

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.