John wrote:
> Hi:
>
> Below is a simple code:
>
> class link1
> {
> public:
> link1();
> link1(int &b1, double &b2);
> int* a1;
> double* a2;
> };
>
> link1::link1(int &b1, double &b2){
> a1 = &b1;
> a2 = &b2;
> }
>
> int main(){
> int c1 = 10;
> double c2 = 0.5;
> link1* c3 = new link1(c1, c2);
>
> int* p1;
> double* p2;
> p1 = c3->a1;
> p2 = c3->a2;
>
> std::cout<<"c3:"<<c3<<" p1:"<<*p1<<" p2:"<<*p2<<std::endl;//LINE1
>
> delete c3; //LINE2
>
> std::cout<<"c3:"<<c3<<" p1:"<<*p1<<" p2:"<<*p2<<std::endl; //LINE3
>
> return 0;
> }
>
> At LINE2, the memory that c3 points to is released, so c3 becomes a
> dangling pointer.
> How about c3->a1 and c3->a2? Are they dangling
> pointers?
Yup. The moment you say c3->x , it invokes UB . You are
trying to access a memory location that has been deallocated / freed.
> Can the memory that c3 pointed to be reallocated now?
Of course - yes.
>
> I ran the code. The output of LINE1 and LINE2 are the same.
Purely coincidental.
--
Karthik.
http://akktech.blogspot.com .
' Remove _nospamplz from my email to mail me. '