In the C language, learning, memory management is particularly important to grasp some knowledge! C before the malloc () and free () the two functions are poorly understood, only know about how to use - is the malloc and free on all OK. Of course, now the two functions are not necessarily more experience, but for the third part of the contents of this article with turning-point understanding of Dao Shi, so
Wrote this article as a summary of knowledge. The reason why this article has a name "of" words, that is, mean it! Hope to have a little help!
If you do not share too much if (for example the operating system virtual memory and physical memory given to how the knowledge of how to manage the class, etc.), I feel this article should be a more comprehensive comment about the malloc () and free () . This article implemented progressively (not necessarily the depth) section describes three main elements.
So much nonsense, immediate access to the following topics ================""""""""""""""""""""""""" """""""""""
1, malloc () and free () the basic concept and basic usage:
1, the function prototype and description:
void * malloc (long NumBytes): This function allocates NumBytes bytes, and returns a pointer to point to this memory. If the allocation fails, it returns a null pointer (NULL).
On the distribution of failure, there should be multiple, for example, is a lack of space.
void free (void * FirstByte): before the function is to allocate space with malloc return the program or operating system, which is released this memory, it re-free.
2, the function of usage:
In fact, these two functions together not that difficult to use, that is, malloc () after that cast off with enough of it to give it to free (), and give a simple example:
/ / Code ...
char * Ptr = NULL;
Ptr = (char *) malloc (100 * sizeof (char));
if (NULL == Ptr)
/ / Code ...
Ptr = NULL;
/ / Code ...
Is it! Of course, the specific situation and specific solutions to specific analysis. For example, you define a pointer, in a function to apply a piece of memory and then through a function Fanhui passed to this pointer, then perhaps the release of this piece of work is Neicunzhexiang should be left to other functions of the.
3, on the function uses a number of areas requiring attention:
A, application memory space, you must check whether the distribution of success.
B, when no need to use the application memory, the recall release; release should point to this piece of memory pointer to NULL, to prevent the process behind the careless use of it.
C, these two functions should be matched. If the application does not release that memory leak; release if that is no reason to do nothing. Released only once, twice, and if more than two will be released
Error (null pointer exception to the release, the release of a null pointer is actually equal to Shaye Mo, so the number of times the release of the release of a null pointer, no problems).
D, although the malloc () function is of type (void *), any type can be converted into a pointer (void *), but the best type of conversion in front of the mandatory, because it can avoid a
More compiler checking.
Well! Probably the most basic thing to say! Now the second part:
Second, malloc () in the end come from where memory space:
1, malloc () in the end from where you got the memory space? The answer is obtained from the heap inside the space. That function returns the pointer is pointing to a heap inside the memory. Operating system has a record of free memory address list. When the operating system before the application process, will traverse the list, then find the first space is greater than the node for the heap space, then the node list from a free node is removed and the knot point of space allocated to the program. Is it!
Here, have another into a small topic, I believe we all know what topics. What is the heap? Speaking of balls, could not help but say the stack! What is stack? The following section is devoted to another to open a small and simple to say about this aside:
2, What is the heap: heap is a shared space, sub-global heap and local stack. The global heap is not allocated all the space, the local heap is allocated user space. Heap in the process of initializing the operating system on time allocation, the operation process can be additional to the system heap, but I remember running out to return the operating system, or else a memory leak.
What is the stack: stack is a unique thread, save the running state and local automatic variables. Stack in the beginning of the initialization thread, each thread's stack, independent of each other. Each function has its own stack, the stack is used to pass parameters between functions. When the operating system will automatically switch thread switch stack, that is, switch SS / ESP register. Stack space in the high-level language which does not require explicit allocation and release.
The concept described above is the standard description, but I delete individual statement is, do not know because it does not become the standard of the ^ _ ^.
On the face of the concept through the description, you can know:
Stack is automatically allocated by the compiler release, storage function parameters, local variables, etc.. Mode of operation similar to the data structure in the stack.
Heap allocation of general release by the programmer, if released, end of the process may recover from the OS. Note here that it is possible, not necessarily. So I would emphasize again, remember to release!
Note that with the heap data structure is different from the methods of distribution Daoshi similar to the list. (Which I mentioned a little above)
So, for example, if you defined above in the function of a pointer variable, and then apply this function in a piece of memory for a pointer point to it. In fact, the pointer's address is in the stack, but the content it points to is in the heap above! It is important to note! So think again, applied in a function in the space, for example, the following functions:
/ / Code ...
void Function (void)
char * p = (char *) malloc (100 * sizeof (char));
On this example, do not think that the function returns, the function where the stack pointer has been destroyed along with the destruction, for the same memory also followed the destruction! This is absolutely wrong! Because the application of memory in the heap, and the function stack where the heap is destroyed with no Sha relationship. Therefore, I reiterate: I remember the release!
3, free () in the end what the release of
The problem is rather simple, but I want to echo the title of second most it! Haha! free () releases the pointer to the memory! Attention! The release of the memory, not a pointer! This is very, very important! Pointer is a variable, only the end of the process only to be destroyed. Free memory space, the original pointer to point to this piece of space still exists! Only now, the contents of the garbage pointer is undefined, so is garbage. Therefore, I have said before, after releasing the memory pointer to NULL, the pointer in the back to prevent it being accidentally Solution references. Ah this is very important!
Well! This "digression" finally end. As simple as that, in a rough idea about him! Here enters the third part:
3, malloc () and free () mechanism:
This part I have a new understanding of today! And is turning-point understanding! Therefore, this part may be a little more understanding of the error! Please help wrong with that!
In fact, a closer look free () function prototype, may also find that it seems magical, free () function is very simple, only one parameter, as long as the transfer point for space pointer
To free () the parameters can be completed in the release of work! Here we tracing to malloc () the application problem. When in fact for the memory than for large. Because of the excess space is used to record information on the management of this memory. A look at the "UNIX high-level programming environment," in Chapter VII of the passage:
Most of the storage space allocated to achieve the required ratio to be slightly larger, additional space for records management information - the length of the block distribution, a distribution point to the next block pointer and so on. This means that if the written end of an allocated area will be rewritten after the piece of management information. This type of error is catastrophic, but because of this error will not soon be exposed, it also difficult to find. Pointer will point to the block allocation may also be rewritten backward movement of the block management information.
The above passage has given us some information on the. malloc () for the space actually I think it is two different kinds of sub-space. One is used to record management information space, another one is available space. And used to record management information is actually a structure. In the C language, with structure to record information with a different object is
A matter of course! Look at the structure following prototype:
struct mem_control_block (
int is_available; / / is a marker?
int size; / / this is the actual size of the space
For size, this is the actual space. Here in fact, I have a question, is_available it is a mark? I saw free () after the source code for this variable feel a bit puzzled (source code analysis below). Also please point out here!
Thus, free () is the basis of this structure information to release malloc () for the space! The structure of two members of the size of the operating system I think things should be. But here there is a problem, malloc () returns a pointer for the space should be pointing to the second space, that is, free space! Otherwise, if the point management information space, then write the type of content and structure may be inconsistent, or will management information blocked, it can not release the memory space, so an error! (Feel where he is being sarcastic)
Well! Look at the following free () the source code, I have analyzed, that the than malloc () source code is much simpler sounds easy. Just have a question, pointed out below!
/ / Code ...
void free (void * ptr)
struct mem_control_block * free;
free = ptr - sizeof (struct mem_control_block);
free-> is_available = 1;
Look at the function, the second sentence, phrase is very important and critical. Sentence is actually a pointer to point to free space to go back, it points to the piece of management information space, because there is less value on the size of a structure! The latter a free-> is_available = 1; I am a bit puzzled! My idea is: there should be only a marker is_available it! Because from this point of view the name of the variable, is_available translates to "can be used." Do not say I land! I think the variable name to reflect the role of a variable, especially strict code. This is the source code, so I think that is absolutely rigorous! ! The value of this variable is 1, that can be used in space! Here I just thought, if it is other value to 0 or do not know what will happen? ! But one thing I am sure that will not release it smoothly! Because this is a tag!
Of course, there may still be some doubt, why this can be released? ? I just have this question. Then I thought, what the operating system release, then free () the source code view, nothing in the release, right? But it really is to determine the management information of the contents of that piece of memory. Thus, free () is only recorded some information, then tell the operating system release that piece of memory can go, how to tell the operating system specific, I do not know, but I think this is beyond the scope of this article I had.
Well, I have a misunderstanding before, is that piece of memory pointer points to move the piece of memory no matter which position can be released that piece of memory! But this is wrong! Is not part of the release of the release! First of all, should understand this point. Moreover, from free () the source code to see, ptr can point to the first address space available, or, after subtracting the size structure of management information must not point to the first address space. Therefore, to ensure that the pointer to the first address space available! Do not believe it? I can write a program and then move the pointer to point to available space, see program will be collapsing!