Dynamic Memory Allocation details, dynamic memory details
(1) dynamic memory allocation
Global variables are allocated to static storage areas in the memory, and local variables are allocated to dynamic storage areas (stacks) in the memory ).
In addition, the C language also has a memory Dynamic Allocation area (HEAP) for temporary data storage ).
Features: you do not have to define part of the program declaration, and you do not have to wait until the function ends. You can open it up and release it at any time. The data can only be referenced by pointers.
(2) Four library functions for dynamic memory distribution
Header files of these four library functions # include
Malloc Function
Void * malloc (unsigned int size)
In the dynamic storage area of the memory, allocate a continuous space with a length of size. The returned value is the starting position of the allocated space. If it fails, null is returned. The base type of the pointer is void, indicating that the pointer does not point to any type of data and only provides one address.
Calloc Function
Void * calloc (unsigned int n, unsigned int size)
Allocate n consecutive spaces with a length of size.
Calloc is often used to allocate space for dynamic arrays. Taking a one-dimensional array as an example, n represents the number of elements, and size represents the length of each element.
Free Function
Void free (void * p)
Releases the dynamic space pointed to by the pointer Variable p. This function has no return value.
Realloc Function
Void * realloc (void * p, unsigned int size );
Realloc is often used to re-allocate, changing the size of the dynamic space pointed by p to size
(3) Small dynamic array example
1 # include
2 # include
3 int main (){
4 void check (int * p );
5 int * p1, I;
6 p1 = (int *) malloc (5 * sizeof (int); // address the first element of the allocated space to p1
7 for (I = 0; I <5; I ++ ){
8 scanf ("% d", p1 + I );
9}
10 check (p1 );
11 free (p1); // release the dynamically allocated space
12}
13
14 void check (int * p ){
15 int I;
16 printf ("failed score :");
17 for (I = 0; I <5; I ++)
18 if (p [I] <60) printf ("% d", p [I]);
19 printf ("\ n ");
20}
Sizeof (int) is the number of bytes occupied by the int data of the current system,
The Return Value of the malloc function is the void pointer type. When you first need to point to int type data, You Need To forcibly convert it to the int type.