C language exercise 61: malloc and free

mallocandfree

 

 

malloc

C language provides a function for dynamic memory allocation:

1 void* malloc (size_t size);

This function applies for a continuous available space in the memory and returns a pointer to this space.

• If the allocation is successful, a pointer to the allocated space is returned.

• If the allocation fails, a NULL pointer will be returned, so the return value of malloc must be checked.

• The type of return value is void*, so the malloc function does not know the type of space to be opened, and the user decides it when using it.

• If the size parameter is 0, the behavior of malloc is undefined by the standard and depends on the compiler. 

free

C language provides another function free, which is specially used to release and recycle dynamic memory. The function prototype is as follows:

1 void free (void* ptr); The free function is used to release dynamically allocated memory.

• If the space pointed to by parameter ptr is not dynamically allocated, the behavior of the free function is undefined.

• If the parameter ptr is a NULL pointer, the function does nothing. Both malloc and free are declared in the stdlib.h header file.

Code display:

#include <stdio.h>
#include <stdlib.h>
int main()
{
	int num = 0;
	scanf("%d", &num);
	int arr[num] = { 0 };
	int* ptr = NULL;
	ptr = (int*)malloc(num * sizeof(int));
	if (NULL != ptr)//判断ptr指针是否为空
	{
		int i = 0;
		for (i = 0; i < num; i++)
		{
			*(ptr + i) = i;
		}
	}
	for (int i = 0; i < 10; i++) {
		printf("%d ", ptr[i]);
	}
	free(ptr);//释放ptr所指向的动态内存
	ptr = NULL;//是否有必要?
	return 0;
}

Guess you like

Origin blog.csdn.net/2301_77479435/article/details/132950047