The malloc and free functions are explained in detail

  • 2020-05-17 06:04:33
  • OfStack

This article covers the malloc and free functions.

In C, the management of memory is quite important. Let's start with these two functions:

1. Basic concepts and usage of malloc() and free() :

1. Function prototype and description:

void *malloc(long NumBytes) : this function allocates NumBytes bytes and returns a pointer to that memory. If the allocation fails, a null pointer (NULL) is returned.

There should be multiple reasons for the allocation failure, such as insufficient space.

void free(void *FirstByte) : this function returns the space previously allocated by malloc to the program or operating system. This function frees up the memory and makes it free again.

2. Function usage:

It's not that hard to use these two functions, which means that malloc() then thinks it's enough and dumps it and gives it to free(), for a simple example:

Program code:


 // Code... 
  char *Ptr = NULL; 
  Ptr = (char *)malloc(100 * sizeof(char)); 
  if (NULL == Ptr) 
   { 
     exit (1); 
   } 
  gets(Ptr); 

  // code... 
  free(Ptr); 
  Ptr = NULL; 
  // code...

That's it! Of course, specific situation wants specific analysis and specific solution. For example, if you define a pointer, claim a block of memory in a function and pass it back to the pointer by function return, then maybe you should leave it to other functions to free up that memory.

3. Some points about the use of functions:

After applying for memory space, you must check whether the allocation is successful.

B, remember to release the requested memory when it is no longer needed; The pointer to this memory should be pointed to NULL after it is freed, in case it is accidentally used later in the program.

C, the two functions should be paired. If it is not released after the application is a memory leak; If you release without cause, you're doing nothing. Release only once, if you release twice or more

An error occurred (except to release a null pointer, which means nothing is being done, so it doesn't matter how many times the null pointer is released).

D, although the malloc() function is of type (void *), and Pointers of any type can be converted to (void *), it is best to cast in the first place because you can avoid some compiler checks.

Now for part 2:

2. Where exactly does malloc() get the memory space:

1. Where does malloc() get its memory space? The answer is to get space from inside the heap. That is, the function returns a pointer to a block of memory in the heap. The operating system has a linked list of free memory addresses. When the operating system receives a request from the program, it iterates through the list, then looks for the heap node whose first space is larger than the requested space, then deletes the node from the free node list, and allocates the node's space to the program. The knowledge of heap can be inquired about the knowledge of data structure or the previous post C/C++ heap, stack and static data area. There is no more to it than that.

2. After using malloc() to allocate memory space, 1 must remember to free the memory space, otherwise there will be a memory leak.

3. What does free() release

free() frees up the memory that the pointer points to! Attention! Free memory, not Pointers! The pointer has not been freed, and it still points to the original storage space. The pointer is a variable that is destroyed only at the end of the program. Free up memory space, the original pointer to this space still exists! It's just that the content that the pointer is pointing to is now garbage, which is undefined, so it's garbage. Therefore, after freeing the memory, point the pointer to NULL to prevent the pointer from being accidentally dereferenced later.

3. Mechanisms of malloc() and free() :

In fact, if you take a closer look at the free() function prototype, you may also find that it seems amazing that the free() function is very simple, with only one parameter. Just pass the pointer pointing to the application space to the free() parameter and you can complete the release! Here's the application for malloc(). The application actually takes up more memory than the application. Because the excess space is used to record the management information of this memory.

Most implementations allocate a bit more storage space than required, with extra space for recording administrative information -- the length of the allocated block, a pointer to the next allocated block, and so on. This means that if the end of an allocated area is written, the management information for the next block is overwritten. This type of error is catastrophic, but because it is not immediately apparent, it is difficult to detect. Moving the pointer back to the allocated block may also overwrite the block's management information.

The space applied by malloc() is actually divided into two Spaces of different properties. One is the space for recording management information, and the other is the free space. The structure that records the management information is actually a structure. In C, structures are often used to record information! Here's a look at the prototype of this structure:

Program code:


 struct mem_control_block { 
 int is_available; //1 Generally speaking, it should be 1 The first address of the available space, but here the English word shows whether the space is available or not 1 A tag 
 int size;   // This is the actual size of the space  
 };

 

 So, free() It's based on the information of this structure malloc() Apply for space! And the size of the two members of the structure I think is a matter of the operating system. 
 Look at the below free() The source code 
   // code... 
 
  void free(void *ptr) 
 { 
   struct mem_control_block *free; 
   free = ptr - sizeof(struct mem_control_block); 
   free->is_available = 1; 
   return; 
 }

As for the source of malloc, you can go to the Internet to find 1!

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: