PDA

View Full Version : Pointer to Pointer



^NyAw^
22nd April 2009, 09:37
Hi,



int* a = new int;
int** b = &a;
delete a;
a = new int;


When creating the new "int" pointer "a", can "**b" be accessed or it will access to a bad memory data?

Thanks,

Lykurg
22nd April 2009, 09:47
b should work fine!

(address=XXX, pointsTo=XXX where XXX are memory addresses)



int* a = new int;

a: address=1 pointsTo=10


int** b = &a;

b: address=2 pointsTo=1 (-> which points to 10)



delete a;

a: address=1 pointsTo=NULL
(b: address=2 pointsTo=1 (-> which points to NULL))



a = new int;

a: address=1 pointsTo=11
b: address=2 pointsTo=1 (-> which points to 11)

^NyAw^
22nd April 2009, 09:58
Hi,

Thanks,

It is what I was expecting.

Lykurg
22nd April 2009, 10:25
Ups, found an error:





delete a;

a: address=1 pointsTo=NULL
(b: address=2 pointsTo=1 (-> which points to NULL))


There "a" still points to "10". So in that short period you have dangling pointers: "a" and "b".

^NyAw^
22nd April 2009, 11:31
Hi,


Ups, found an error:



There "a" still points to "10". So in that short period you have dangling pointers: "a" and "b".

Yes but this is not a problem because I have QMutex to lock this kind of operations.

Thanks,

caduel
25th April 2009, 08:00
A pointer just (a the name says) points to a piece of memory.
When you free that memory all accesses to it become invalid, both 'direct' ones (via the freed pointer) and also all other ways you manage to access the address of the freed memory.

So in your example, you may neither access *a or **b.
(The pointers themselves are valid, but the memory finally pointed to, is not.)