Can anyone tell me what's a dangling pointer? An example? As a matter, I'm a little confused on the concept of pointer in C/C++.
Printable View
Can anyone tell me what's a dangling pointer? An example? As a matter, I'm a little confused on the concept of pointer in C/C++.
A pointer is a memory location that points to another memory location. A pointer which is not pointing to anything, is dangling...
int *pVariable;
... is dangling, it has random contents. Stylistically, it is always better to declare a pointer thus...
int *pVariable = 0;
... then later you can test to see if the pointer is dangling because no real world pointer would have the value 0. Now...
pVariable = new int;
... is no longer dangling, because you have created a memory location on the heap, (see the other thread!), and the pointer is pointing to it.
int pVariable;
Are you sure about that Adrian? pVariable is pointing to something (Usually 0xCCCCCCCC on Win32), you just don't know what it is. If, on the other hand, you had:-
int *pVariable;
I'd be inclined to agree.
Yeah, typo, we're talking about pointers, they were supposed to be pointers!
Note to self, avoid answering questions whilst drinking breakfast tea.
Ok, thanks for answering but I'm still a little unclear. You say a dangling pointer is dangling if it doesnt point to anything, but then you also said a pointer always point to something? huh?
> a pointer always point to something?
If you don't tell the pointer what to point to (by initializing it), the value of the pointer is just random garbage from memory, so it's still technically pointing to something, but it's almost definitely nothing of any use.