How does malloc implement dynamic memory allocation and malloc dynamic memory allocation?
Summary on the Internet:
(1) Static allocation: it is allocated on the stack. It is applied by the user and released by the operating system.
Dynamic Allocation: it is allocated by the compiler. This mechanism is not provided by the operating system. Therefore, you must delete the application on your own!
(2) You also need to understand that the stack capacity is very small and extremely expensive and cannot meet all memory applications, so dynamic allocation is required,
(3) the dynamic allocation is completed by the compiler and has nothing to do with the operating system.
(4) Dynamic Allocation Efficiency is relatively low, but the capacity is related to user requirements.
(5) Use malloc and free in C, and use new and delete in C ++.
(6) malloc requires a parameter for allocating memory size. How can it be dynamic?
See the following example:
# Include <iostream> # include <string> # include <cstdlib> using namespace std; void main () {int * p; p = (int *) malloc (sizeof (int) * 10); for (int I = 0; I <11; I ++) {* (p + I) = I ;}for (int I = 0; I <11; I ++) cout <* (p + I) <""; system ("pause ");}
Note:That is to say, we use malloc to allocate 10 int-sized spaces. We can also dynamically assign values to 11th int values to achieve dynamic memory expansion, allocating int num [10] with static memory cannot be completed.