malloc and free dynamically open up space and release

malloc

In the definition of the array, we know that the opening of the array space is static, that is, we can have the following affirmation methods;

int arr[5];

The above development method has two characteristics:
1. The space development size is fixed.
2. When the array is declared, the length of the array must be specified. The memory it needs is allocated at compile time.
However, sometimes we hope that the size of the array can be based on The length of the array is set according to the wishes of the user, so there are common mistakes such as the following:

int a;
printf("please input the size you want");
scanf("%d",&a);
int arr[a];

Does this seem to be impeccable, but unfortunately, such an array declaration method is not allowed in the C language. Therefore, we need to use a new type of space development method: dynamic development . The more typical one is to use malloc. The development of space.

void *malloc( size_t size );

This function means to apply for a continuous available space from the memory and return a pointer to this fast space.
Corresponding to it, there is also a free function to release the dynamically opened memory.

void free (void* ptr);

For example, the following code:

#include<stdio.h>
int main()
{
    
    
	int* pl = NULL;
	int size;
	printf("请输入你所想要数组元素的个数");
	scanf("%d", &size);
	pl = (int*)malloc(size*sizeof(int));//申请一块连续的内存大小
	if (NULL != pl)//判断是否开辟成功
	{
    
    
		int i = 0;
		for (; i < size; ++i)
		{
    
    
			*(pl + i) = i;
		}
	}
	free(pl);//释放空间
	pl = NULL;//释放指针
	return 0;
}

Through the code, we can know that the use of a correct and complete dynamic development must pay attention to the following points:
malloc:
1. If the development is successful, it returns a pointer to open up a good space
2. If the development fails, it returns a NULL pointer, Therefore, the return value of malloc must be checked
. 3. The return type refers to void*, so the malloc function does not know the type of space opened, and the size inside must be opened according to the number of bytes
. 4. If the parameter size is 0, malloc The behavior standard of is undefined, and it is determined by different compilers, so the ambiguity of such use is large, and it is generally not recommended to use this method.
free:
1. As long as it is a dynamically opened space, it needs to be released when the space is no longer used.
2. If the space pointed to by pl is not dynamically opened, it cannot be released
3. If the parameter pl is a NULL pointer, what does the function do? nor do
[Note]
dynamic open space pointer NULL return value must be judged, ie to determine whether to open up the success;
the use of free space just been released, then the pointer is still there, but the meaning space is not available, it is necessary Release the pointer.

Guess you like

Origin blog.csdn.net/dream_i_success/article/details/110499840