Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two pointers pointing to the same address [closed]

Tags:

c++

c

pointers

What happens when two pointers are pointing to the same address? Is this going to cause a security problem?

like image 296
Daneshju M Avatar asked Apr 29 '12 08:04

Daneshju M


People also ask

Can 2 pointers point to the same address?

Yes, two pointer variables can point to the same object: Pointers are variables whose value is the address of a C object, or the null pointer.

Can a pointer point to 2 things?

Yes. A pointer p to type T can point to a single T , or to an array of T .

Can 2 pointers be compared?

We can compare pointers if they are pointing to the same array. Relational pointers can be used to compare two pointers. Pointers can't be multiplied or divided.

Do pointers have their own addresses?

The main feature of a pointer is its two-part nature. The pointer itself holds an address. The pointer also points to a value of a specific type - the value at the address the point holds.


1 Answers

The fact itself is ok, but you'll run into undefined behavior if you call delete on one of the pointers and attempt to use the other afterwards:

int* x = new int(5);
int* y = x;
delete x;
//y is a dangling pointer

If you run into a situation where you have to use multiple pointers to the same memory address, you should look into smart pointers.

like image 117
Luchian Grigore Avatar answered Nov 15 '22 12:11

Luchian Grigore