Stack, stack, heap and stack differences

Source: Internet
Author: User

In the C language learning, the memory management of this part of the knowledge is particularly important.

Basic concepts and basic usage of malloc () and free ():

1. Function prototype and description: void *malloc (Long numbytes): This function allocates numbytes bytes and returns a pointer to this memory. If the allocation fails, a null pointer is returned (NULL). There should be a number of reasons for the allocation failure, such as a lack of space. void *firstbyte: This function returns the space previously allocated by malloc back to the program or the operating system, which frees up the memory and lets it regain its freedom.

2, the use of functions: In fact, these two functions are not very difficult to use, that is, malloc () after feeling that it was enough to dump it to free ().

3. Some places to note about function use:

A. After you have applied for memory space, you must check whether the assignment was successful.

B, when you do not need to use the requested memory, remember to release; After release, the pointer to this memory should be pointed to NULL, prevent the program accidentally used it.

C, the two functions should be paired. If it is not released after the application is a memory leak, if it is released for no reason, nothing is done. Release can only once, if released two times and more than two times an error (releasing null pointer exception, releasing the null pointer is actually equal to nothing, so release the null pointer released how many times no problem).

D, although the type of the malloc () function is (void *), any type of pointer can be converted to (void *), but it is better to make a forced type conversion before, as this will avoid some compiler checks.

Stack, stack, heap, and stack differences

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.