Malloc function of dynamic memory management

 Introduction:  

Digression: Learning 1. pointers, 2. structures, and 3. dynamic memory allocation is helpful for learning data structures.

Nowadays, when we write code, we will apply for space from the computer, and now there is only one way to apply for space that we have learned, one is int (applying in small pieces), and the other is int [ ] (one Apply in chunks).

 However, the space applied for by our method is fixed and the size cannot be changed, which is not convenient.

In C language, we have the ability to make the memory size we apply for large or small. This is what dynamic memory management does. Among them, the most core ones in dynamic memory management are malloc, calloc, ralloc, and free.

Next, let's learn the malloc function.

The definition of malloc function can be found in cplusplus.com:

 After checking, after using malloc, a space of size size will be opened and a pointer will be returned pointing to the starting position of the memory block. When applying for space, will the application fail? After the application fails, a null pointer will be returned. If size is 0, the behavior of the malloc function is undefined and depends on the compiler.

The free function is used to release dynamically allocated memory: 1. If the space pointed to by the parameter ptr is not dynamically allocated, the behavior of the free function is undefined; 2. If the parameter ptr is a NULL pointer, the function does nothing.

 

 

 

Below is the code written to use the malloc function:

 Let me introduce what INT_MAX is? After turning to the definition, it is more than 2.1 billion.

 Let’s explain that the space requested by int and the space requested by the malloc function are in different areas:

The malloc function corresponds to the free function. After the memory application is made, the applied space needs to be released, so as not to cause memory leaks (in layman's terms, you borrowed a book, but you didn't change it, so others can't see it). There is no free in the above code, which does not mean that the memory space will not be reclaimed. When the program exits, the system will automatically reclaim the memory space.

The free function is used to release the requested space. After the space is released, p also points to the address returned by the malloc function. If p is not pointed to null, p will become a wild pointer.

Malloc and free should appear in pairs as much as possible to prevent memory leaks.

Now we are writing an endless loop to apply for space. The computer will not give out space uncontrollably and will not cause the computer to crash. If there is a memory leak in a program that needs to run 7 times 24 hours, it will be very scary and the system will need to be restarted in a few days. . 

Guess you like

Origin blog.csdn.net/2301_77868664/article/details/130837228
Recommended