动态内存分配(malloc).c

*The so-called Dynamic Memory Allocation refers to the method of allocating Memory by dynamically allocating or recovering storage space in the process of program execution.Dynamic memory allocation does not require pre-allocation of storage space as static memory allocation methods such as arrays do. Instead, the system allocates storage space immediately according to the needs of the program, and the size of the allocation is the size required by the program.
Function malloc prototype is void malloc(unsigned int size);Its purpose is to allocate a continuous space of size in the dynamic storage area of memory.The return value of this function is the starting address of the allocation field, or it is a pointer function that returns a pointer to the beginning of the allocation field.
Returns a pointer to allocated memory if the allocation is successful (the initial value in this store is uncertain), otherwise returns NULL pointer NULL when memory is no longer in use, use the free() function to properly align the pointer returned by the memory block release function so that it can be used with any data object.
As for the prototype of this function, in the past, malloc returned a char pointer. The new ANSIC standard stipulates that this function returns a void pointer, so it can apply to the system to allocate a block of memory with the length of num bytes(or size).
In general, it needs to pair with the free function to use the free function to release a dynamically allocated address, indicating that this dynamically allocated memory is no longer used, and the previous dynamically applied memory is returned to the system.

The following procedures test the memory in your computer can be currently allocated:
在这里插入图片描述

//   Date:2020/3/15
//   Author:xiezhg5
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
	void *p;
	int count=0;
	while((p=malloc(100*1024*1024)))
	{
		count++;
	}
    printf("您的电脑分配了%d00MB的空间\n",count);
    free(NULL);
    return 0;
}
发布了52 篇原创文章 · 获赞 25 · 访问量 1279

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/104877817
今日推荐