C Advanced Memory Management (2)

Dynamic memory allocation functions malloc() and free()

When we need to dynamically apply for a memory space, we can use the malloc() function to open up a space in the heap area in memory. When this memory is no longer used to store data, the free() function must be used to free this memory.

For the specific introduction of these two functions, you can use the man command to view it under the shell. The viewing method is as follows:

man 3 malloc

man 3 free

 

Function prototype: void* malloc(unsigned int size);

Parameters: The size of the memory to be applied for (unit: bytes)

Return value: void* pointer (success) or NULL (failure)

illustrate:

1. The void* type pointer cannot be used directly. The void* type pointer must be converted into a pointer of the specified type through forced type conversion. If you want to store int type data in the requested memory, you need to convert it to (int *). If If you want to store char data in the allocated memory, you need to convert it to (char *).

2. The return value is NULL, which means that the memory application failed, so it must be determined whether the return value is NULL.

 

Function prototype: void free(void *p)

Parameters: the address to be released

Return value: none

illustrate:

1. If the memory space after malloc is used up, if it is not released, it is easy to cause memory leaks.

2. The free() function releases a pointer. This pointer must be set to NULL. Otherwise, after the free() function is called to release the memory space pointed to by the pointer, the pointer is not a null pointer. At this time, the pointer belongs to a wild pointer and stores an unknown block. memory address. If the second free() is used, the memory space of this unknown memory address will be released, which may easily cause the system to crash.

 

Example: Use the malloc() function to apply for a space to store an array. This array is used to store integers. The size of the array is manually entered. The data stored in the array also needs to be entered manually, and the area is reclaimed after use.

#include <stdio.h>

#include <stdlib.h>

 

int main(int argc, const char *argv[])

{

       you, n;

       int*p = NULL;

       printf("Inputthe size of array!\n");

       scanf("%d",&n);

       p= (int *)malloc(sizeof(int) * n);

       if(p== NULL)

       {

              perror("Mallocerror!");

              return1;

       }

 

       i= 0;

       while(i< n)

       {

              printf("Input%d nummer\n",i+1);

              scanf("%d",p+i);

              i++;

       }

       printf("Youinput number as follows!\n");

       for(i= 0; i < n; i++)

       {

              printf("%d",*(p+i));

       }

       printf("\n");

       free(p);

       p= NULL;

       printf("Mallocmem release!\n");

 

       return0;

}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325418586&siteId=291194637