C and pointer (pointers on C) -- Chapter 11th: dynamic memory allocation (I)
Chapter 2 dynamic memory allocation
When an array is declared, it is itself a pointer constant, and the memory has been allocated during compilation. However, sometimes the program does not know how long the array exists. Therefore, to prevent memory waste, C provides a dynamic memory allocation policy.
In fact, as an independent chapter, this chapter does not have much content. Malloc, free, calloc, and realloc are useless, but they contain many usage and many traps.
Summary:
Both the malloc and calloc functions are used to dynamically allocate a memory and return a pointer to the memory. Malloc returns a void * pointer.
The malloc parameter is the number of bytes of memory to be allocated. The calloc parameter is the number * unit length.
The realloc function can change the size of a dynamically allocated memory.
Void * malloc (size_t size); or void * malloc (num) * sizeof (...))
Void free (void * pointer );
Void * calloc (size_t num_elements, size_t element_size );
Void realloc (void * ptr, size_t new_size );
If the first parameter of realloc is ptr = NULL, it returns the same value as malloc, a NULL pointer.
When a piece of memory is no longer used, you should call the free function to return it to the memory pool. However, if it is not returned by the malloc, calloc, or realloc function, it cannot be passed as a parameter to free.
Memory leakage means that the memory is not released when it is no longer used after it is dynamically allocated. Memory leakage increases the size of the program.
Warning:
1. Do not check whether the pointer returned from the malloc function is NULL.
# Include
# Include
Array = malloc (10 * sizeof (int ));
If (array = NULL)
Exit (EXIT_FAILURE );
2. access areas outside the dynamically allocated memory.
3. Pass a pointer to the free function that is not returned by the malloc function.
It does not work at all.
4. Access the dynamic memory after it is released.
Programming tips:
1. dynamic memory allocation helps eliminate internal restrictions of the program.
2. Use sizeof to calculate the length of the Data Type to improve program portability.
For 32-bit and 16-bit machines, int is different in bytes. Therefore, sizeof (int) is recommended ).