Tracing Dynamic Memory

View Code

The last tracing is for dynamic memory. No matter how experienced in programming a person maybe they will always, always, ALWAYS trace dynamic memory. It is the most complex as both values and spots for them are kept track.

Depending on what language or level of Computer Science used this can wait till latter. Also read up on the language's specifics for dynamic memory, i.e. references and pointers to be sure.

Pointers

int x = 2;
int *p = new int(4);
*p = &x;
*p = 3;
p = null; 
   
Diagram of this code block
  1. Declare integer x with value 2.
  2. Declare pointer p with initial new integer with a value of 4.
  3. P is assigned to the address of x, i.e. p points to x.
  4. Object of p is assigned 3.
  5. P is set to NULL.
  6. At the end, x is 3, there is a loose integer with a value of 4, and p is NULL.
  7. With this tracing notice how the memory leak of that 4 by itself.
int *p, *q = new int(0);
p = q;
*q = 3; *p = 2;
delete p;
q = new int(4);
delete q;
p = q = NULL;
	 
Diagram for this code block
  1. Declare two pointers to integers p and q. Q pointes to a new interger with a value of 0;
  2. P points to the same thing as q.
  3. Object which q points to is 3. Object which p points (which is the same integer q points to) is 2.
  4. Delete the integer p points to, so p and q point to nothing.
  5. Q points to a new integer (new box) with a value of 4.
  6. Integer which q points to is deleted.
  7. P and q are set to point to NULL.

References

int x = 4;  int &r = x; int *p;
p = &x;
r = 2;
*p = 5;
p = new int(2);
int &s = *p;
p = NULL;
s = 1; 
	 
Diagram for this code block
  1. Declare an integer x, reference to an interger r which referes to x, and a pointer to an integer p.
  2. P points to the address of x.
  3. R is assign 2, (and so is x).
  4. Object which p points to (x) is 5.
  5. P points to a new integer with a value of 2.
  6. A reference to an integer s is declared, and refered to the object which p points to.
  7. P points to NULL.
  8. S is assigned 1.

Prev -- Back to Portal -- Next