Follow the rules below when you are asked to draw a diagram.
Rules 1-3
- For each stack frame of a function, draw a scratch pad. Label the pad with
the function name.
- All local variables should reside inside the corresponding pad. Label them.
- Draw a box only for an object that is occupied in the memory.
- A variable should have a box, since its value is stored in memory.
- A constant value should not have a box.
Example 1
void f(char );
int main()
{
int n = 4;
char c = 'h';
f(c);
return 0;
}
void f(char c)
{
double x = 4.7;
cout << c << endl;
//*** point1 ***
}
|
|
- Rule 1 is satisfied. There are two pads labeled with main and f.
- Rule 2 is satisfied. You can see all the local variables properly labeled.
- Rule 3 is satisfied. There are four boxes.
|
Example 2
void f(char );
int main()
{
int n = 4;
f('h');
return 0;
}
void f(char c)
{
double x = 4.7;
cout << c << endl;
//*** point1 ***
}
|
|
Observe how rule 3-2 is applied in the slighted changed code.
|
Rules 4-5
- If an array is located in the heap area, the array should be drawn
outside the stack frame (scratch pad) of any function.
- Inside each box, specify the value that it stores.
- For example, the box contains an
int, give an actual integer value.
- If the box contains an
address (i.e., if it's a pointer
variable), give an arrow that starts from inside the box.
Example 3
void f(char );
int main()
{
int n = 4;
int* A;
A = new int[n]{1, 3, 5, 7};
f('h');
return 0;
}
void f(char c)
{
double x = 4.7;
cout << c << endl;
//*** point1 ***
}
|
|
- Rule 4 is satisfied, since the array is outside of the pads.
- Rule 5 is satisfied. Note how the arrow is drawn for variable A.
- The starting point is inside the box.
- The ending point is the first element of the array.
Rules 6
- When two pointers are equal, they point to the same thing.
Example 4
void f(int* B);
int main()
{
int n = 4;
int* A;
A = new int[n]{1, 3, 5, 7};
f(A);
return 0;
}
void f(int* B)
{
B[1] = 0;
//*** point1 ***
}
|
|
Example 5
void f(int* q);
int main()
{
int n = 4;
int* A;
A = new int[n]{1, 3, 5, 7};
int* p = &A[2];
f(p);
return 0;
}
void f(int* q)
{
*q = 0;
//*** point1 ***
}
|
|
Rules 7
- When the function is finished, the scratch pad should be
discarded.
Example 6
int* f();
int main()
{
int* A;
A = f();
//*** control point 2 ***
return 0;
}
int* f()
{
int* B = new int[4] = {1, 3, 5, 7};
//*** control point 1 ***
return B;
}
|
control point 1
|
|
between control points 1 and 2
|
control point 2
|