A reference to the reference to the normal pointer release memory

xiaoxiao2021-03-06  55

A reference to the reference to the normal pointer release memory

First, see a piece of code first:

#include

Using namespace std;

Void FreePtr1 (INT * P1)

{

Delete P1;

P1 = NULL;

}

Void FreePtr2 (INT * & P2)

{

Delete P2;

P2 = NULL;

}

void main ()

{

INT * p1 = new int;

* p1 = 1;

FreePTR1 (P1);

INT * p2 = new int;

* p2 = 2;

FreePTR2 (P2);

System ("pause");

}

Thinking: Can you find them different points in FreePTR1 and FreePTR2?

Second, explain the code:

#include

Using namespace std;

Void FreePtr1 (INT * P1)

{

// Not released before memory -> p1 address: 0012fddc p1 value: 003429b8, here, P1 is also a variable, since it is a variable, then it will pass the external variable P1 to the stack with the value of the value, An address is generated in the stack: 0012FDDC, of ​​course, its value does not change still point to the pile of addresses: 003429b8.

Delete P1; / / The system reclaims the memory at address 003429b8 at the P1 value.

P1 = NULL; // Taking the NULL value of P1: 00000000, Note: The address of the P1 itself is not changed, and the value of P1 is changed.

/ / After release memory -> p1 address: 0012fddc p1 value: 00000000, after the stack, P1 is automatically considered to be invalid after the stack is out.

}

Void FreePtr2 (INT * & P2)

{

// No memory -> p2 address: 0012FEC8 P2 Value: 003429b8, P2 is a reference to a pointer, that is, reference pointed pointer, remember the characteristics of reference: Direct operation of the referenced object. Therefore, its address and value are the same as the main () function outside the stack.

DELETE P2; / / / / The pointer referenced by P2 is released, ie: the system reclaims the memory of the value 003429b8 address in the main () function.

P2 = null; // The pointer to the main () function is defined in a null value.

// Release memory -> p2 address: 0012FEC8 P2 Value: 00000000

}

void main ()

{

INT * p1 = new int;

/ / Pre-release memory -> p1 address: 0012FED4 P1 value: 003429B8

FreePTR1 (P1);

// Release memory -> p1 address: 0012FED4 P1 value: 003429B8

INT * p2 = new int;

// Release memory before -> P2 Address: 0012FEC8 P2 Value: 003429B8

FreePTR2 (P2);

/ / After release memory -> p2 address: 0012FEC8 P2 Value: 00000000

System ("pause");

This is three months later, once again picked up C start school, the above example can make the beginner (of course, I also include it), you can have a new or another understanding of the reference and pointer. Everyone said, good memory is not as bad as a mess, although it is a relatively simple question) ... ^ _ ^, if there is any difference, or personal opinion, please leave a message, thank you.

Thanks again, the Perfect Wasteman (WOLF) provides an example ...

转载请注明原文地址:https://www.9cbs.com/read-114062.html

New Post(0)