Notes for the memory allocation malloc function.

Source: Internet
Author: User

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.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.