Use of malloc and free

Source: Internet
Author: User
Tags int size

1. How to use the malloc function

Do not be confused, in fact, this small dialogue above, is the use of malloc process. Malloc is a function that is dedicated to allocating memory from the heap. There are several requirements to use the malloc function:

Who is the memory allocated to?
How much memory is allocated?
Are there enough memory allocations?
What format of data will the memory be used to store, i.e. what is memory used for?
Where is the allocated memory?

If these five points are OK, then the memory can be allocated. The following is a first look at the prototype of the malloc function:

1 (void *) malloc (int size)

See no, here the return type is (void *), which is how ingenious a design ah.

The return value of the malloc function is a pointer of type void, and the parameter is of type int, which is the amount of memory requested for allocation, in bytes. After the memory allocation succeeds, the malloc function returns the first address of the memory. You need a pointer to receive this address. However, because the return value of a function is of type void *, it must be cast to the type you receive. That is, this memory will be used to store what type of data. Like what:

1 Char *p = (char *) malloc (100);

Allocate 100 bytes of memory on the heap, return the first address of the memory, cast the address to char * Type and assign the pointer variable p to char * type. It also tells us that this memory will be used to store data of type char. This means that you can only manipulate this memory with the pointer variable p. The memory itself does not have a name, and access to it is anonymous.
  

Above is the process of successfully allocating a chunk of memory using the malloc function. But, every time you can assign success.

Not necessarily.

The function should also note this: if the requested memory block is larger than the remaining memory block (the whole block) on the heap, the memory allocation fails and the function returns NULL. Note that the "Heap of memory remaining" is not the sum of all the remaining blocks of memory, because the malloc function is requesting contiguous chunks of memory. Since the malloc function has failed to request memory, we must use if (NULL) when using pointers to this memory. =P) statement to verify that the memory is indeed allocated successfully.

2. Request 0-byte memory with the malloc function

Another problem: requesting 0-byte memory with the malloc function returns a null pointer.
You can test it, or you can find the documentation for the malloc function. To request 0 bytes of memory, the function does not return NULL, but instead returns a normal memory address. But you can't use this 0-size memory. A tick on this good ruler, the scale itself is not of length, only a certain two scale together to measure the length. Be careful with this because if (NULL). =P) Statement validation will not work.

3. Memory Release

Since there is a distribution, it must be released. Otherwise, the limited memory will always run out, while the memory that is not freed is idle. What corresponds to malloc is the free function. The free function has only one parameter, which is the first address of the block of memory to be freed. For example, the above example:

1 Free (p);


The free function looks pretty tough, but what exactly does it do?

In fact, it does one thing: the relationship between the cut-off pointer variable and this block of memory.

For example above, we can say that the malloc function allocates memory blocks that belong to P, because our access to this memory needs to be done through P. The free function is to sever all relationships between this memory and P. There is no more involvement between p and that piece of memory. As for the pointer variable p itself holds the address unchanged, but it has no ownership of the memory at this address. The stored value of the freed memory has not changed, but it is no longer available.

This is the function of the free function. According to the above analysis, if you use the free function for p more than two consecutive times, an error will definitely occur. Because the first use of the free function, p belongs to the memory has been released, the second time the use of no memory can be freed. On this point, I (Chengzhong teacher) in class to let the students remember is: must be monogamous, or must be wrong.

malloc two times only free memory leaks; If malloc is free two times, it will definitely go wrong. In other words, the number of malloc used in the program must be equal to free, or there must be an error. This error mainly occurs when the malloc function is recycled, and the malloc and free times are often mistaken.

4. After the memory is released

Since the address saved by the pointer variable p itself after using the free function does not change, then we need to re-convert the value of p to null:

1 p = NULL;

This null is the "chain of wild dogs" we said before. If you don't tie it up, it'll be a problem sooner or later. Like what:

After free (p), you use if (NULL. =P) Such a check statement can also play a role.
For example:

1 2 3 4 5 6 7 8

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.