StartC ++ Memory ManagementDiscuss:
First look at a program:
- int main()
- {
- int i=10;
- int *j=&i;
- if(!0)
- {
- int l=20;
- int *k=&l;
- j=k;
- k=0;
- }
- cout<<*j;
- return 0;
- }
No compiler. Do you think about what results should be printed after execution? I think the first response is to print an uncertain number. The reason is that in the if statement, we define the k variable. After the if statement is executed, the memory occupied by k is reclaimed by the system, as a result, the result indicated by variable j is very uncertain. Of course, after compilation and execution, we find that the final print result of the program is 20, which is not an uncertain number we expect. Let's analyze the cause!
We use the debug Method for step-by-step analysis, and input all the variables in the watch window.
- Int I = 10; // I is 10 and & I is 0x0012ff7c
- Int * j = & I; // * j is 10 and & j is 0x0012ff7c
- // Obviously, the two variables refer to the same address.
- If (! 0)
- {
- Int l = 20; // l is 20 and & l is 0x0012ff74
-
- /* The address 0x0012ff7c-0x0012ff75 is occupied. It should be noted that,
- This value may vary depending on the computer hardware. */
-
- Int * k = & l; // * k is 20 and & k is 0x0012ff74
-
- // The variable k and l point to the same address.
-
- J = k; // j is 0x0012ff74 and * j is 20
-
- /* Assign values between pointers. This statement is to assign the negative value of the address pointed by k to j.
- The two variables point to the same address, both of which are 0x0012ff74.
- The block address is 20, so * j is 20. */
- }
-
- Cout <* j; // * j is 20 and j is 0x0012ff74
-
- /* The k address is 0x00000000, indicating the k variable.
- It has been automatically destroyed, so the address is zero. However, j does not refer to k,
- Is the address 0x0012ff74 that k refers to, and because j's lifecycle is still
- J is accidentally defined in if), so the address that j points to is
- If it is not recovered, the number 20 is saved. */
At this point, we have analyzed the memory allocation throughout the entire process of the program. The final result is as follows:
We can also look at the specific content of this address in Memory. We can see that it is 14, which is a hexadecimal number, converted to decimal, exactly 20. As shown in:
Now you should have a rough understanding of the execution process of the above program! However, this is not the expected result. What we need is to print an uncertain result. With the above analysis, we started a new program and asked him to print what we wanted.