I have heard that dangling pointer problem arises when we assign same address to two different pointers. That is due to both pointers point to same memory location and if memory is freed using address in one pointer; it can still be accessible from the second pointer(or even from the first pointer, if not set to null, I am not discussing this case).
In the following code, I have tried different scenarios in which same memory location should be assigned to different pointers, but apparently in every scenario it is allocating new memory. Why is it so? In every case deep copies are being created.
#include<iostream>
using namespace std;
class Player
{
public:
char * name;
char * countryName;
char * gameName;
int age;
Player()
{
}
Player(char * n, char * c, char * g,int a)
{
name=n;
countryName=c;
gameName=g;
age=a;
}
};
void printAddresses(Player p,Player p3)
{
cout<<endl<<&p3<<endl<<&p<<endl;
cout<<endl<<&p3.name<<endl<<&p.name<<endl;
cout<<endl<<&p3.countryName<<endl<<&p.countryName<<endl;
cout<<endl<<&p3.gameName<<endl<<&p.gameName<<endl;
cout<<endl<<&p3.age<<endl<<&p.age<<endl;
}
int main()
{
Player *p2=new Player;
Player *p4=p2;
// p2 is a pointer and p4 is also a pointer initialized from p2. But the following function prints the memory addresses, and it shows that both objects have different memory addresses. And data members also have different memory locations
printAddresses(*p4,*p2);
return 0;
}
I have also tried a lot of scenarios for initializing the pointers. But in each case it appears that they have separate memory addresses, and also corresponding data members also have different memory addresses.
So in which case dangling pointer problem can arise here? OR how can I make a shallow copy here? Is this c++ standard/version(written below) behaves like this or am I missing something?
OS : Linux mint 15
Output of g++ --version:
g++ (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
Copyright (C) 2012 Free Software Foundation, Inc.