Introduction to malloc and free in C (1)

Source: Internet
Author: User
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:

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, 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)

Article reference from: http://www.bc-cn.net/bbs/dispbbs.asp? Boolean id = 5 & id = 82212

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.