I'm having a hard time understanding how to tell between dangling pointers and memory leaks. I have a few questions on a recent assignment that are puzzling me, and after reading into it, I am still puzzled. I don't want someone to do my homework for me, I want to be able to understand why something is what it is, if that makes sense.
So, the homework:
Given the declarations:
int *ptrA, *ptrB;
Tell whether each code segment below results in a memory leak, a dangling pointer, or neither. Draw pictures to help.
ptrA
is already pointing to something in memory, so this one is neither a dangling pointer or a memory leak.ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = ptrA;
ptrB
points to nothing.ptrA = new int;
*ptrA = 345;
ptrB = ptrA;
delete ptrA;
ptrA = new int;
ptrB = new int;
*ptrA = 345;
*ptrB = *ptrA;
ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = new int;
*ptrB = *ptrA;
ptrA = LocationOfAge();
where function LocationOfAge
is defined as:
int *LocationOfAge() {
int age = 21;
return &age;
}
Thanks for anyone willing to help.
The rules of the game:
new Type
draw a box. Put a question in the box (you don't know what is in there).delete p
cross out the box pointed to by p
.a = b
(where there are no stars) draw a line from variable a
to a box b
.*x = y
write y
inside the box pointed at by x
.*x = *y
read the content of the box y
and put a copy in x
The result:
The first problem:
ptrA = new int;
ptrB = new int;
*ptrA = 345;
ptrB = ptrA;
Lets do this line by line:
ptrA = new int;
// Part 1 has a new so draw a box
*********
* ? *
*********
// Part 2 assignment to variable add a line
ptrA -------> *********
* ? *
*********
ptrB = new int;
// Part 3 has a new so draw another box
ptrA -------> *********
* ? *
*********
*********
* ? *
*********
// Part 4 assignment to variable add a line
ptrA -------> *********
* ? *
*********
ptrB -------> *********
* ? *
*********
*ptrA = 345;
ptrA -------> *********
* 345 *
*********
ptrB -------> *********
* ? *
*********
ptrB = ptrA;
ptrA -------> *********
| * 345 *
| *********
|
ptrB ---- *********
* ? *
*********
Seems like you have a leaked box. i.e. There is a box with no variable pointing at it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With