I. Why dynamic memory allocation?
When we do not learn the linked list, we always use an array to store a large number of data of the same type or structure. For example, if we want to store the scores of a certain student in a class, we always define a float type (with 0.5 points) array:
Float score [30];
However, when using arrays, there is always a problem: How big should an array be?
In many cases, you cannot determine the size of the array to be used. For example, if you do not know the number of students in the class, you need to define the array large enough. In this way, yourProgramAt runtime, you have applied for a fixed size of memory that you think is large enough. Even if you know the number of students in the class, if the number of students increases or decreases for some special reason, you must modify the program again to expand the storage range of the array. This method of allocating a fixed size of memory is called static memory allocation. However, this memory allocation method has serious defects, especially when dealing with some problems: In most cases, a large amount of memory space is wasted. In a few cases, when the defined array is not large enough, it may cause subscript out-of-bounds errors or even serious consequences.
Is there any other way to solve this problem? Yes, that is, dynamic memory allocation.
The so-called dynamic memory allocation refers to the way in which the allocated memory of the storage space is dynamically allocated or recycled during program execution. Unlike static memory allocation methods such as arrays, dynamic memory allocation requires pre-allocation of storage space. Instead, the system allocates the storage space in real time based on program requirements, and the allocated size is the size required by the program. From the above comparison, we can know the characteristics of dynamic memory allocation compared with Jingtai memory allocation:
1. No pre-allocated storage space is required;
2. The allocated space can be expanded or reduced as needed by the program.
Ii. How to Implement Dynamic Memory Allocation and Management
To dynamically allocate buckets Based on program needs, the following functions must be used:
1. malloc Function
The following is a prototype of the malloc function:
Void * malloc (unsigned int size)
The function is to allocate a continuous space with a length of size in the dynamic storage area of the memory. The parameter is an unsigned integer, And the return value is a pointer to the starting address of the allocated continuous storage domain. Note that a null pointer is returned when the function fails to allocate storage space (such as insufficient memory. Therefore, when calling this function, check whether the returned value is null and perform corresponding operations.
The following example shows a program for Dynamic Allocation:
# Include
# Include
Main ()
{
Int count, * array;/* count is a counter, and array is an integer pointer. It can also be understood as pointing to the first address of an integer array */
If (array = (int *) malloc (10 * sizeof (INT) = NULL)
{
Printf (the bucket cannot be allocated successfully .);
Exit (1 );
}
For (COUNT = 0; count <10; count ++)/* assign values to arrays */
Array [count] = count;
For (COUNT = 0; count <10; count ++)/* print array elements */
Printf (% 2D, array [count]);
}
In the above example, 10 integer storage areas are dynamically allocated, and then assigned and printed. In this example, if (array = (int *) malloc (10 * sizeof (INT) = NULL) statements can be divided into the following steps:
1) allocate 10 integer continuous buckets and return an integer pointer pointing to its starting address.
2) Assign this integer pointer address to array
3) check whether the returned value is null.
2. Free Functions
Because the memory area is always limited, you can allocate it without limits, and a program should save resources as much as possible. Therefore, when the allocated memory area is not used, it should be released, for other variables or programs. Now we need to use the free function.
Its function prototype is:
Void free (void * P)
The function is to release the memory zone pointed to by pointer p.
The parameter P must be the pointer returned when you call the malloc function or calloc function (another function that dynamically allocates the storage region. Passing other values to the free function may cause crashes or other catastrophic consequences.
Note: What is important here is the pointer value, rather than the pointer itself used to apply for dynamic memory. Example:
Int * P1, * P2;
P1 = malloc (10 * sizeof (INT ));
P2 = p1;
......
Free (P1)/* or free (P2 )*/
The return value of malloc is assigned to P1, and the value of P1 is assigned to P2. Therefore, P1 and P2 can be used as parameters of the free function.
The malloc function allocates storage areas.
The free function is used to release unused memory areas.
Therefore, these two functions can achieve dynamic allocation and simple management of the memory area.
Original text from [than the Internet], reproduced Please retain the original link: http://soft.chinabyte.com/database/350/11200350.shtml
"Dynamic" (dynamic) memory allocation means that the system allocates storage space as needed when the program is running. Note that the allocated space should be released in time after use, otherwise the remaining memory space will become smaller and smaller, affecting system operation.
In C language, common malloc () and calloc () functions are used to dynamically obtain memory space.
1. malloc () and free () Functions
The malloc () and free () functions are the most common dynamic memory allocation and release functions in C language.
Malloc () Format: pointer = malloc (space size );
For example, PTR = malloc (100); this command requires the computer to allocate a continuous bytes of space. The malloc () function returns the first address of the space and stores it in the PTR.
Free () Format: Free (pointer); // release the area indicated by the pointer
Example: char * P;
P = (char *) malloc (8); // open up an 8-byte storage space, assign the address to the pointer P, and access the space through the pointer p.
* P = 'l'; // storage characters. The allocated space is 0th bytes in storage.
* (P + 1) = 'O'; // the first byte of the allocated space is stored as 'O '.
* (P + 2) = 'V ';
* (P + 3) = 'E ';
* (P + 4) = '\ 0 ';
Puts (p); // output string
Free (p); // release space
Note: * (p + n) is equivalent to P [N], (p + n) is the address, and * (p + n) is the address (p + n).
For example, in the above Program * (p + 1) = 'a'; P [1] = 'A' can be written ';
The parameters of the malloc () function can be constants, variables, or expressions. In addition to storing strings, malloc () can also obtain space to store integer and other data. For example, the storage integer allocation space is as follows:
Int * PTR;
PTR = (int *) malloc (sizeof (INT) * 4 );
Malloc () opens up a space to store four integers. Because malloc () returns a 0th-byte address in total and the return value must be of the char * type, you must pass (int *) to forcibly convert to an integer and save the pointer PTR to the integer.
When space is allocated using the malloc () function, if the computer cannot provide sufficient space for allocation, a null pointer is returned. Therefore, if the returned pointer is null, it indicates that the available space is insufficient.