"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.
Bytes ----------------------------------------------------------------------------------------------
C language Dynamic Distribution System
C language memory allocation
The C language provides three methods for memory allocation: static allocation, dynamic allocation, and stack creation.
Static Allocation refers to allocating corresponding space to variables in the Data Segment of the Program (process) during compilation, such as global variables and static variables. They exist throughout the process, the compiler controls allocation and release completely.
The memory created on the stack is also controlled by the compiler and used to store function parameters and non-static local variables. When the function is executed, real parameters and local variables are pushed into the stack. After the function is executed, the variables in the stack are pushed out of the stack.
Dynamic Allocation (Dynamic Allocation) is a method for the program to obtain or return the memory from the heap as needed during runtime. The allocated memory is controlled by the programmer. during runtime, the compiler does not automatically delete them, but the programmer determines their lifetime.
Pointer and dynamic memory allocation/Dynamic Allocation Function
Pointers in C language provide necessary support for the dynamic allocation system. C's dynamic allocation function:
# Include <stdlib. h>
Void * malloc (size_t size );
Void * calloc (size_t nitems, size_t size );
Void * realloc (void * block, size_t size );
Void free (void * block );
Malloc () allocates a memory space of size, points to the space with a void pointer, and returns the pointer. If the memory in the heap is insufficient, the function fails, null Pointer is returned.
The following code allocates 1000 bytes to the heap. After the result is returned, it assigns a value to the character pointer PTR. PTR points to the first address of the 1000 bytes:
Char * PTR;
Int * iptr;
PTR = malloc (1000);/* allocate bytes */
Iptr = malloc (50 * sizeof (INT);/* allocate memory for 50 integers */
Here, when the return value of the malloc () function is assigned to PTR and iptr, you do not need to use forced type conversion (the pointer expression). However, you must note that malloc () the memory allocated by the function is not initialized, that is, the value in the memory is uncertain.
Although the free memory in the heap is usually large, it is still limited, so the allocation function may fail and a null pointer is returned. Therefore, after the allocation function is called, check its return value to ensure that the pointer is valid; otherwise, program paralysis may occur.
Calloc () is also used to allocate memory on the stack, but the size of the allocated space is determined by nitems
* The size is determined, that is, the amount of allocated memory is equal to the size of nitems. Compared with the malloc () function, the space allocated by calloc () is initialized to zero, which is filled with 0.
Realloc () is used to change the size of allocated memory space. This function is different between c89 and c99. In c89, The realloc () function changes the size of the previously allocated memory directed by the block to the size. The size value can be greater than or less than the original value. During reallocation, the content in the old block (maximum size byte) is copied to the new block. In c99, the block is idle and new blocks are allocated. The new block contains the same content as the old block (maximum size. The function returns a pointer to the new block, which can be the same as the address of the old block. Therefore, the returned pointer can be consistent with the passed pointer. If the block is a null pointer, then, realloc
() The function only allocates memory of size bytes and returns the result. If the size is zero, the realloc () function releases the memory pointed to by the block.
Free () is used to release the space allocated by the dynamic allocation function. Its parameter is a pointer to a space. Note that the block must be obtained after being allocated using the dynamic allocation function (the above three functions. If an Invalid Pointer is passed in, the free () function may destroy the memory management mechanism and paralyze the system. If the block is null, the free () function does not operate.
Dynamically-allocated Array)
Note that the dynamic array and dynamic array (dynamic array/growable array/resizable array/dynamic table/array list) are differentiated. The latter is like STD: vector in C ++.
(1) dynamically allocated one-dimensional array
1/* dynamically allocated one-dimensional array */
2 # include <stdlib. h>
3 # include <stdio. h>
4 # include <string. h>
5
6 int main ()
7 {
8 char * s;
9 register int T;
10
11 S = malloc (80);/* allocate */
12 if (! S) {/* Check pointer */
13 printf ("memory allocation failed ");
14 exit (1 );
15}
16
17 get (s );
18 For (t = strlen (S)-1; t> = 0; putchar (s [T]);/* reverse print */
19
20 free (s);/* release */
21 return 0;
22}
(2) dynamically allocated two-dimensional array
1/* dynamically allocated two-dimensional array */
2/* calculate a table ~ ~ Power */
3 # include <stdlib. h>
4 # include <stdio. h>
5
6 int PWR (INT, INT );
7
8 int main ()
9 {
10/* pointer to the integer array with the number of elements */
11 int (* iptr) [10];/* the parentheses here are required */
12 register int I, J;
13
14 iptr = malloc (40 * sizeof (INT);/* sizeof ensures portability */
15 if (! Iptr) {/* Check pointer */
16 printf ("memory allocation failed ");
17 exit (1 );
18}
19
20 For (j = 1; j <11; j ++)
21 For (I = 1; I <5; I ++) iptr [I-1] [J-1] = PWR (J, I );
22
23 For (j = 1; j <11; j ++ ){
24 For (I = 1; I <5; I ++) printf ("% 10d", iptr [I-1] [J-1]);
25 printf ("\ n ");
26}
27
28 free (iptr);/* release */
29 return 0;
30}
31
32 PWR (int A, int B)
33 {
34 register int T = 1;
35
36 For (; B; B --) t = T *;
37
38 return T;
39}
Common Errors of dynamic memory allocation
Common memory allocation errors include:
(1) The memory allocation function returns a null pointer and uses the pointer returned without checking. The Return Value of the function should be checked while the function is returned to prevent misuse.
(2) reference the memory returned by the malloc () function before initialization.
(3) operations on the allocated memory crossed the boundary. For example, the subscript "more than 1" or "less than 1" during Array Operations ".
(4) forget to call the free () function to release the memory when exiting the program block, resulting in Memory leakage. The application and release of dynamic memory allocation must be paired, and the usage of malloc and free in the program must be the same.
When free () is used to release the memory, the corresponding pointer is not set to null, resulting in "Dangling Pointer ).
Call the free () function to release the memory, but continue to use it.
The free () function is called to release the memory, and the free () function is called again later to release it.