Hi guys,
This is actually a very silly question considering I should already know this, but I figured I'd ask just to be sure.
Let's say I have the following syntax:
Cat *c = new Cat(55); //55 is the cat's age :)
Would deleting the Cat object involve the following 2 lines?
delete c;
c = null;
6 replies to this topic
#1
Posted 19 December 2010 - 08:19 PM
|
|
|
#2
Posted 20 December 2010 - 09:03 AM
That would be correct.
A conclusion is where you got tired of thinking.
#define class struct // All is public.
#3
Posted 20 December 2010 - 01:11 PM
Flying Dutchman said:
That would be correct.
TCristoforo, To delete the object, you would simply call:
delete c;
The "c = NULL;" line would point it to void (nothing!), and helps identify accidental usage of it.
The segmentation fault should say you attempted to modify memory around "0" (it'll be higher, but close to 0).
It's always a good idea (I think!) to point it to NULL after it has been deallocated, however.
“You may be disappointed if you fail, but you are doomed if you don't try.”
- Beverly Sills
- Beverly Sills
#4
Posted 20 December 2010 - 01:59 PM
Thanks guys, I'm dealing with some memory leaks and wanted to confirm the basics of the process :)
Here's another question along the same lines.
Let's say I have the following
Cat *c = new Cat(55);
Cat *newCat = null;
newCat = c;
delete newCat;
newCat = null;
I read this as 2 pointers pointing to the same object, which is deleted. Now my understanding is that neither pointer is pointing to a legit object, but only newCat is null, is this also correct?
Here's another question along the same lines.
Let's say I have the following
Cat *c = new Cat(55);
Cat *newCat = null;
newCat = c;
delete newCat;
newCat = null;
I read this as 2 pointers pointing to the same object, which is deleted. Now my understanding is that neither pointer is pointing to a legit object, but only newCat is null, is this also correct?
#5
Posted 20 December 2010 - 02:07 PM
Yea, only newCat is deleted and points to NULL. c is still there (somewhere :) )
A conclusion is where you got tired of thinking.
#define class struct // All is public.
#6
Posted 22 December 2010 - 07:29 PM
Clarification: c still points somewhere, but the data that it points to is no longer valid.
sudo rm -rf /
#7
Posted 25 December 2010 - 07:31 PM
Exactly. Which is why there should be only ever one 'official' pointer to an object. If there are two, and you delete one, the other becomes what is called a "dangling pointer." Writes through a dangling pointer can cause errors, or even worse, mangle some other object's data silently, and you only find out when you see that Mittens' name is suddenly "\x7fK.!~" because you told Snowball to eat.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users


Sign In
Create Account


Back to top









