-
July 7th, 2010, 09:29 AM
#1
Why this small code snippet gives runtime error?
Code:
#include <iostream>
using namespace std;
class A
{
int* ptr;
public:
A(int* i)
{
ptr=new int;
ptr=i;
}
A& operator=(A &x)
{
if(this==&x)
{
return *this;
}
else
{
delete this->ptr;
this->ptr=0;
this->ptr=new int;
this->ptr=x.ptr;
}
return *this;
}
void show()
{
cout<<*ptr;
}
~A()
{
cout<<"Inside ~A()"<<endl;
if(ptr!=0)
delete this->ptr; //ERROR CASUSES HERE
this->ptr=0;
}
};
int main()
{
int* i=new int;
int* j=new int;
*i=10;
*j=20;
A a1(i);
A a2(j);
a1=a2;
a1.show();
}
Output:
20
Inside ~A()
Inside ~A()
RUNTIME EROOR
Last edited by forumuser11@gmail.com; July 8th, 2010 at 02:08 AM.
-
July 7th, 2010, 09:32 AM
#2
Re: Why this small code snippet gives runtime error?
Code:
A(int* i)
{
ptr=new int;
ptr=i;
}
Well you're leaking memory here.
If you'll use code tags I'm sure that the fact that you're copying the object is causing a double delete.
-
July 7th, 2010, 09:54 AM
#3
Re: Why this small code snippet gives runtime error?
Code:
#include <iostream>
using namespace std;
class A
{
int* ptr;
public:
A(int* i)
{
ptr=new int;
*ptr=*i;
}
A& operator=(A &x)
{
if(this==&x)
{
return *this;
}
else
{
delete this->ptr;
this->ptr=0;
this->ptr=new int;
*(this->ptr)=*(x.ptr);
}
return *this;
}
void show()
{
cout<<*ptr;
}
~A()
{
cout<<"Inside ~A()"<<endl;
if(ptr!=0)
delete this->ptr; //ERROR CASUSES HERE
this->ptr=0;
}
};
int main()
{
int* i=new int;
int* j=new int;
*i=10;
*j=20;
A a1(i);
A a2(j);
a1=a2;
a1.show();
}
Output:
20
Inside ~A()
Inside ~A()
RUNTIME EROOR
Remember you need to deference your pointers, to copy the values they point to, rather than copy the actual pointers.
Off topic: Don't you know how to use code tags by now?...
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
-
July 7th, 2010, 12:00 PM
#4
Re: Why this small code snippet gives runtime error?
Originally Posted by forumuser11@gmail.com
</code>
You should have seen that this does not work for code tags. Do you not read your own posts?
[code] Your code goes here [/code]
Regards,
Paul McKenzie
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|