Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Usage of malloc function in C language>?
Usage of malloc function in C language>?

Malloc in C language is a dynamic memory allocation function.

Function prototype: void *malloc(unsigned int num_bytes).

Parameters: num_bytes is an unsigned integer used to represent the number of allocated bytes.

Note: When the memory is no longer used, the free() function should be used to release the memory block. The pointer returned by the function must be properly aligned so that it can be used with any data object. Regarding the prototype of this function, malloc previously returned a char pointer. The new ANSIC standard stipulates that this function returns a void pointer, so type conversion is required when necessary.

Method to implement malloc:

First we must determine the data structure used. A simple and feasible solution is to organize the heap memory space in the form of blocks. Each block consists of a meta area and a data area. The meta area records the meta-information of the data block (data area size, free flag bit, pointer, etc.).

The data area is the actual allocated memory area, and the first byte address of the data area is the address returned by malloc.