Memory Allocation in function calls in C ++

Source: Internet
Author: User

Memory Allocation in function calls in C ++

I. Memory Allocation

Before talking about function calls and return values, let's take a look at the issue of memory allocation in C ++.


The C ++ compiler divides computer memory into code and data areas. Obviously, the Code zone stores program code, while the data zone stores variables and constants during program compilation and execution. The data zone is divided into static data zone and Dynamic Data zone. The dynamic data zone includes the heap zone and stack zone.

The role of each zone is as follows:

(1) code area: stores program code;

(2) Data Zone

A. Static Data zone:
The memory allocated to the variable during compilation by the compiler. The data stored in this zone is automatically released after all programs are executed. The Life Cycle runs throughout the entire program execution process.

B. Dynamic Data zone: including heap zone and stack Zone


Heap zone: This part of the storage space is managed by the programmer himself, and its distribution and release are all the responsibility of the programmer himself. This zone is the only one where the programmer can decide the lifetime of the variable. You can use malloc and new to apply for memory and release space through free and delete. If the programmer applies for space in the heap area and forgets to release the memory, it will cause memory leakage and will not be able to access the storage area.


STACK: stores the form parameters and local variables of the function, which are allocated and automatically released by the compiler. After the function is executed, the space occupied by the local variables and parameters is automatically released. Efficiency is relatively high, but the allocated capacity is very limited.

 

Note: 1) global variables and static variables are stored in the static data zone;

2) Pay attention to the storage area of constants. Normally, constants are stored in the program area (the program area is read-only, so any behavior to modify constants is illegal), rather than the data area. Some systems also allocate some constants to static data areas, such as string constants (some systems also allocate them to the program area ). Remember that the memory space of a constant is protected by the system and cannot be modified. Modifying the constant space will cause access to memory errors. Generally, the system will prompt you. The life cycle of a constant until the execution of the program ends.

 

Example of memory allocation:

Int A = 1; // A in the stack Area

Char s [] = "123"; // s is in the stack zone, "123" is in the stack zone, and its value can be modified

Char * s = "123"; // s is in the stack zone, "123" is in the constant zone, and its value cannot be modified.

Int * P = new int; // P is in the stack zone, and the applied space is in the heap zone (P points to the zone)

Int * P = (int *) malloc (sizeof (INT); // P in the stack zone, P points to the space in the heap Zone

Static int B = 0; // B is in the static Zone

 

Ii. function call


After learning about the memory allocation problem, let's take a look at the function call process:

When a function is executed, if a parameter exists, space is allocated for the form parameter on the stack (except for Parameters of reference type; if the parameter is an object, call its "copy constructor" to allocate space and assign values to the parameter.) continue to the function body. If a variable is encountered, allocate space for variables in different storage areas as needed (for static variables, space is allocated during compilation ), after the statement in the function is executed, if the function does not return a value, it will directly return the place where the function is called (that is, the execution is far away). If the return value exists, then, the return value is copied (if it is an object, its "copy constructor" is called) and a back-to-stack operation is performed, release the memory space applied for in the function stack.

 

Here are a few examples to talk about memory allocation and function return values:

1. Pass the value to call the function. Modifications to the form parameters in the function are not reflected outside the function.

Class student {public: Char name [10]; int age ;}; void edit (student Stu) {Stu. age = 30;} void cmfctestdlg: onbnclickedbutton3 () {student s; sprintf (S. name, "Tom"); S. age = 29; Edit (s); // here S. age is still 29}

 

2. Call the function through address transfer. Modifications to the form parameters in the function will be reflected outside the function.

Class student {public: Char name [10]; int age ;}; void edit (student * Stu) {stu-> age = 30; // or, the following method also affects student s; sprintf (S. name, "Jerry"); S. age = 33; * Stu = s;} void cmfctestdlg: onbnclickedbutton3 () {student s; sprintf (S. name, "Tom"); S. age = 29; Edit (& S); // here S. age is still 30}

 

3. Use the pointer parameter to apply for memory. Use the pointer to the pointer instead"

Void getmemory2 (char ** P, int num) {* P = (char *) malloc (sizeof (char) * num);} void Test2 (void) {char * STR = NULL; getmemory2 (& STR, 100); // note that the parameter is & STR, not STR strcpy (STR, "hello "); cout <STR <Endl; free (STR );}

 

4. Use the function return value to pass the dynamic memory. This method is simpler and easier to understand.

char *GetMemory3(int num){ char *p = (char *)malloc(sizeof(char) * num); return p;}void Test3(void){ char *str = NULL; str = GetMemory3(100); strcpy(str, "hello"); cout<< str << endl; free(str);}

 

5. Although it is easy to use the function return value to pass dynamic memory, some people often use the return statement wrong. It is emphasized that the return statement should not be used to return the pointer pointing to the "stack memory", because the function will automatically die when it ends.

Char * getstring (void) {char P [] = "Hello World"; return P; // the compiler will warn} void test4 (void) {char * STR = NULL; STR = getstring (); // STR content is junk cout <STR <Endl ;}

 

6. Return the pointer of the "static storage area" using the function return value.

char *GetString2(void){ char *p = "hello world"; return p;}void Test5(void){ char *str = NULL; str = GetString2(); cout<< str << endl;}

 

Although the preceding example 6 does not run correctly, the design concept of the getstring2 function is incorrect. Because "Hello World" in getstring2 is a constant string located in the static storage zone, it remains unchanged during the lifetime of the program. No matter when getstring2 is called, it returns the same read-only memory block.

 

 

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.