Reputation: 353
i am getting glibc detected in the following code can someone please explain it to me
#include<iostream>
using namespace std;
class Sample
{
public:
int *ptr;
Sample(int i)
{
ptr = new int(i);
}
void PrintVal()
{
cout << "The value is " << *ptr<<endl;
}
~Sample()
{
cout<<"CALLED\n";
delete ptr;
}
};
void SomeFunc(Sample x)
{
cout << "Say i am in someFunc " << endl;
x.PrintVal();
//cout<<*(s1.ptr)<<endl;
}
int main()
{
Sample s1=10;
cout<<*(s1.ptr)<<endl;
SomeFunc(s1);
cout<<"HERE\n";
cout<<*(s1.ptr)<<endl;
}
Here on calling cout<<*(s1.ptr)<<endl;
the glib is detected. what i am not able to understand is why even when desructor is not called for s1 the reference is getting deleted.
Upvotes: 1
Views: 313
Reputation: 23001
For any class that inludes resources that need to be released in the destructor, it's best practice to create a copy constructor for that class as well as an assignment operator to avoid problems like these.
That said, there would have been no need for the copy to occur in the first place, if you had declared the SomeFunc function to take a const reference, which would also be far more effecient.
void SomeFunc(const Sample &x) {
...
}
Upvotes: 0
Reputation: 5998
The problem is that you don't have a copy constructor and you have a dynamically allocated member data.
void SomeFunc(Sample x)
creates a new copy of s1
. And x
and s1
's ptr
s will be pointing to the same location. Once the function SomeFunc
returns that memory is deleted (when x is destroyed.)
And when main returns s1
is destroyed. Now your destructor tries to delete
a memory location which is already deleted and you have double free or corruption
error.
A simple copy constructor for your case
Sample(const Sample& s)
{
ptr = new int(*(s.ptr));
}
You don't really seem to use pointers and dynamic allocation here. However if you have to use dynamic allocation consider taking a look at Rule of three and smart pointers.
Upvotes: 6