The full name of malloc is memory allocation, which is called dynamic memory allocation. It is used to apply to the system for allocating the specified bytes of memory space.
Prototype: extern void * malloc (unsigned int num_bytes );
It is a headache to see the prototype. Here are two examples:
*= ( *) malloc (()*);
*pd=( *) malloc (()*);
The two statements show the usage of malloc:
It is also a pointer. The Return Value Type of the malloc function is void *, but the void * type can be forcibly converted to any other type of pointer. It is equivalent to malloc and can return any type of pointer.
Forced conversion is needed almost wherever malloc is used, because no one should use a void type to process actual data.
Sizeof () is used almost wherever malloc is used.
That is:Type * pointer = (type *) malloc (sizeof (type ));
This prototype looks much easier.
Notes:
When using malloc to dynamically apply for memory blocks, it is best to determine the return value.
If the allocation fails, NULL pointer is returned.
When the memory is no longer used, use the free () function to release the memory block.
We recommend that you develop the habit of forced conversion.
Malloc is different from new:
New returns a pointer of the specified type and automatically calculates the required size.
Malloc requires us to calculate the number of bytes and forcibly convert it to a pointer of the actual type after the return.
Example 3:
stu *=( stu *)malloc(( stu));
Using the formula above, we can easily write out our own example. Example 3 first defines a structure pointer pb, realallocates the memory space of a structure, and assigns the first address to pb;
When we use a linked list, it is very practical to use malloc to allocate space.