How to know the size of the space to be released when the library function free

Reprint: Please indicate the source, http://blog.csdn.net/zonghongyan314/article/details/41786037 Thank you!

malloc, free functions:

malloc is a standard library function for dynamic memory allocation in C/C++. The function prototype is void* malloc(unsigned int size); its function is to dynamically open up memory space on the heap. Its characteristics:
1. The return value is void*, (void* type can be cast to any other type of pointer, but not vice versa);
2. The size of the space to be allocated needs to be specified, and the size type is an unsigned integer type;
3. It allows to apply for 0 Length of memory (this is very interesting);
4. The space applied for is logically continuous and physically discrete (managed in the form of a linked list).
So the question is, after malloc allocates space, how do you know the size of the space to be free when free releases the space?

In fact, the real memory management, such as application/release, is not handled by library functions such as malloc or free, but by the operating system. They just maintain a free linked-list memory block. Understanding this is a problem. key. For example: to apply for a memory space of sizeof(int)*100, although the returned memory size is 400, in fact, when the operating system allocates, there will be an extra piece of stuff like the head node of the linked list used to store the memory size. East, this node stores the first address of the space and the size of the allocated memory. When the user calls the free function, in fact, it does not know the size of the memory to be released. It only needs to change the size of the memory in the head node. The release of the specific memory space is done by the operating system.

Guess you like

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