Linux C heap Memory management function malloc (), Calloc (), realloc (), free () detailed

Source: Internet
Author: User

In C programming, memory that is often required to operate can be divided into the following categories:

    1. Stacking area (Stack): Automatically allocated and disposed by the compiler, parameter values for stored functions, local variables, temporary variables, and so on, all of which are obtained automatically by the compiler.
    2. Heap Area (heap): Generally by the programmer allocation and release, the base programmer does not release, the program ends may be recycled by the operating system (c/s, no such recycling mechanism, java/c#), note that it is different from the heap in the data structure, distribution is similar to the linked list.
    3. Global Zone (Static zone): The storage of global variables and static variables is put together, initialized global variables and static variables in an area, uninitialized global variables and uninitialized static variables in another adjacent area. Released by the system after the program is finished.
    4. Literal constant: The constant string is placed here and released by the system at the end of the program.
    5. Program code area: binary code that holds the body of the function.

The C standard function library provides a number of functions to implement memory management on the heap, including the malloc () function, the free () function, the calloc () function, and the realloc () function. Use these functions to include the header file stdlib.h. Their declarations are as follows:

  • void * malloc (size_t N);
  • void free (void * p);
  • void *calloc (size_t n, size_t size);
  • void * ReAlloc (void * p, size_t N);

1. malloc () function

The malloc () function can obtain the memory space of a specified byte from the heap, and its function is declared as follows:

void * malloc(size_t N);

where parameter n is the number of bytes required to allocate. If the function executes successfully, malloc () returns the first address of the memory space, or null if the function execution fails. Because the type of the malloc () function value is a void pointer, it is possible to convert its value type to an arbitrary type pointer so that the memory space obtained from the heap can be manipulated by manipulating the type pointer.

It is important to note that thememory space allocated by the malloc () function is uninitialized. Therefore, in general, when using this memory space, call another function memset to initialize it to full 0. The declaration of the Memset function is as follows:

void * memset (void * p, int c, size_t N);

The function can place the specified memory space in bytes to the specified character C. where P is the first address of the memory space to be zeroed, C is the value to set, and N is the byte length of the memory space being manipulated. If you want to clear 0 with memset, the variable C argument is 0. The operation statements for the malloc () function and the memset function are generally as follows:

int *p = NULL;P = (int *) malloc (sizeof (int)), if (p = = NULL) {printf ("Can ' t get memory!\n");} memset (p, 0, sizeof (int));

Note: Heap memory obtained through the malloc () function must be initialized using the memset () function.

Example code:

#include <stdio.h> #include <stdlib.h> #include <string.h>int main () {int *p = NULL;P = (int *) malloc (siz EOF (int)); if (NULL = = p) {printf ("Can ' t get memory!\n"); return-1;} printf ("%d\n", *p);//output allocates the value of the Space memset (p, 0, sizeof (int)),//The space that the P points to 0printf ("%d\n", *p);//output calls memset function after the result *p = 2; printf ("%d\n", *p); return 0;}

2. Free () function

Memory space obtained from the heap after the program finishes, the system does not automatically release it and requires the programmer to manage it. At the end of a program, you must ensure that all the memory space obtained from the heap has been safely released, otherwise it will cause a memory leak. For example, a memory leak will occur on the demo above.

The free () function implements the ability to release memory. Its function declaration is:

void free (void * p);

Because the formal parameter is a void pointer, the free () function can accept any type of pointer argument.

However, the free () function simply releases what the pointer points to, and the pointer still points to the point where the pointer is a wild pointer , which causes an unexpected error if the pointer is manipulated at this point. The security practice is to set the value of the pointer to null after releasing the space that the pointer points to using the free () function. Therefore, for the above demo, you need to return

The following two lines of statements are added before the statement:

Free (p);p = NULL;

Note: Heap space allocated using the malloc () function must be freed before the program ends.

3. Calloc () function

The function of the calloc () function is similar to the functionality of the malloc () function, which allocates memory from the heap. Its function is declared as follows:

void *calloc(size_t N, size_t size);

The function return value is a void type pointer. If the execution succeeds, the function obtains a size X n byte space from the heap and returns the first address of the space. If execution fails, the function returns NULL. When this function differs significantly from the malloc () function, the memory space obtained by the calloc () function is initialized, and its contents are all 0. The Calloc () function is suitable for an array requisition space, which can be set to the space length of an array element, and N to the capacity of an array.

Example code:

#include <stdio.h> #include <stdlib.h> #define SIZE 5int Main () {int *p = Null;int i = 0;//assign p from the heap SIZE int type space p = (int *) calloc (SIZE, sizeof (int)), if (NULL = = p) {printf ("Error in calloc.\n"); return-1;} The size int type space to which p points is assigned for (i = 0; i < SIZE; i++) {p[i] = i;} Outputs the values for each space for (i = 0; i < SIZE; i++) {printf ("p[%d]=%d\n", I, P[i]);} Free (p);p = Null;return 0;}

Tip: The allocated memory of the CALLOC () function also needs to be released on its own.

4. ReAlloc () function

The functions of the realloc () function are richer than the malloc () function and the calloc () function, and can implement memory allocation and memory deallocation functions, which are declared as follows:

void * realloc(void * p, size_t N);

Where pointer p must be a pointer to the heap memory space, that is, a pointer to the space allocated by the malloc () function, the calloc () function, or the realloc () function. The ReAlloc () function changes the size of the memory block pointed to by the pointer p to n bytes. If n is less than or equal to the amount of space pointed before P, then. Keep the original state unchanged. If n is greater than the amount of space previously pointed to by P, then the system will re-allocate a chunk of memory space from the heap to P, while the contents of the original point to the space are copied sequentially to the new memory space, and the space previously pointed to is freed. the space allocated by the realloc () function is also uninitialized.

Note: Using the malloc () function, the memory space allocated by the calloc () function and the realloc () function is freed using the free () function or the null realloc () function of the pointer argument.

Example code:

#include <stdio.h> #include <stdlib.h>int main () {int *p = NULL;P = (int *) malloc (sizeof (int)); *p = 3;printf ("p  =%p\n ", p);p rintf (" *p=%d\n ", *p);p = (int *) realloc (p, sizeof (int));p rintf (" p=%p\n ", p);p rintf (" *p=%d\n ", *p);p = (int *) ReAlloc (P, 3 * sizeof (int));p rintf ("p=%p\n", p);p rintf ("*p=%d", *p);//release P-Pointing space realloc (p, 0);p = null;return 0;}

The following points to note are:

    1. Both the function malloc () and calloc () can be used to dynamically allocate memory space. The malloc () function has a parameter, that is, the size of the allocated memory space, and malloc () retains a certain amount of space to record allocations when allocating memory, and the more time they allocate, the more space these records occupy. In addition, depending on the malloc () implementation strategy, malloc () may allocate more space each time it is allocated than is actually required, and multiple allocations lead to more such waste, of course, which is related to the implementation of malloc () ; the calloc () function has two parameters , which are the number of elements and the size of each element, the product of the two parameters is the size of the memory space to allocate. If the call succeeds, they will return the first address of the allocated memory space.
    2. The main difference between the function malloc () and Calloc () is that the former cannot initialize the allocated memory space, while the latter can.
    3. ReAlloc () can expand or shrink the space indicated by a given pointer, whether it expands or shrinks, and the contents of the original memory will remain unchanged. Of course, for shrinking, the content of the part that is shrunk is lost.
    4. ReAlloc () does not guarantee that the adjusted memory space and the original memory space remain the same memory address, whereas the pointer returned by REALLOC () is likely to point to a new address. So in the code, we have to reassign the return value of ReAlloc () to P: p = (int *) realloc (p, sizeof (int) *);

realloc ()function, another point of note:

ReAlloc () There is a possibility that the operation fails and returns NULL, so do not assign its return value directly to the original pointer variable, lest the original value be lost:

#include <stdio.h> #include <stdlib.h>int main () {char *str = NULL;STR = (char *) malloc (sizeof (char)); *str = ' A '; char *p = (char *) realloc (str, sizeof (char) *); if (P! = NULL) {str = p;} printf ("%s\n", str); return 0;}

Reference:

Http://baike.baidu.com/view/736230.htm

Linux C heap Memory management function malloc (), Calloc (), realloc (), free () detailed

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.