Write based on Monster group and GPT:
malloc functions can be used to dynamically allocate memory in order to allocate the required size of memory when the program is running. The function prototype is as follows:
void* malloc(size_t size);
Where, size indicates the number of bytes to be allocated, and the return value is the first address of the allocated memory. If allocation fails, NULL is returned.
For example, to allocate an array of type int, you would use the following code:
int* arr;
int n = 10;
arr = (int*) malloc(n * sizeof(int));
Here we first define a pointer to int arr, and then use malloc to allocate n * sizeof(int) bytes of memory, that is, the amount of memory that can hold n int variables. Since malloc returns a pointer to type void*, it needs to be cast to a pointer to type int.
When the allocated memory is used up, it should be freed using the free function to avoid memory leaks. For example, to free the memory allocated in the above code, you can use the following code:
free(arr);
Here frees up the memory space to which the pointer arr points.