How does malloc implement dynamic memory allocation and malloc dynamic memory allocation?

Source: Internet
Author: User

How does malloc implement dynamic memory allocation and malloc dynamic memory allocation?

Summary on the Internet:

(1) Static allocation: it is allocated on the stack. It is applied by the user and released by the operating system.

Dynamic Allocation: it is allocated by the compiler. This mechanism is not provided by the operating system. Therefore, you must delete the application on your own!
(2) You also need to understand that the stack capacity is very small and extremely expensive and cannot meet all memory applications, so dynamic allocation is required,
(3) the dynamic allocation is completed by the compiler and has nothing to do with the operating system.

(4) Dynamic Allocation Efficiency is relatively low, but the capacity is related to user requirements.

(5) Use malloc and free in C, and use new and delete in C ++.

(6) malloc requires a parameter for allocating memory size. How can it be dynamic?

See the following example:

# Include <iostream> # include <string> # include <cstdlib> using namespace std; void main () {int * p; p = (int *) malloc (sizeof (int) * 10); for (int I = 0; I <11; I ++) {* (p + I) = I ;}for (int I = 0; I <11; I ++) cout <* (p + I) <""; system ("pause ");}


Note:That is to say, we use malloc to allocate 10 int-sized spaces. We can also dynamically assign values to 11th int values to achieve dynamic memory expansion, allocating int num [10] with static memory cannot be completed.

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.