Reputation: 23
#include <iostream>
#include <string.h>
using namespace std;
class sir{
int lung; //sir lenght
char* sirul; //pointer to the first character form sir
public:
sir(const char*);//constructor,for test
~sir();// destructor
char operator[](int index);
int cod();
};
int sir::cod()
{
sir u=*this;
char* s=sirul;
int i,sum,l=lung;
if (lung=0)
cout<<"ASCII code sum is 0";
else
{
for(i=0; i<l; i++)
{
sum=sum+int(s[i]);
}
}
return sum;
}
sir::sir(const char* siroriginal)
{
int lungime=strlen(siroriginal);//string length
lung = lungime+1;
sirul = new char[lung];
strcpy(sirul,siroriginal);
}
sir::~sir(){
delete sirul;
}
char sir::operator[](int index){
if(index<lung && index >=0)return sirul[index];//verificare minima, verific daca este in limite
return '\0';
}
int main(){
cout<<"--------------test for sir-----------------\n";
sir s("un sir meserias");
char c=s[1];
cout<<c<<"\n";
cout<<s.cod();
}
When I'm executing this program an error says that "double free or corruption", I don't understand what causes this error. It appears after I'm trying to calculate ASCII code sum of my sir(string) with cod
method, that should return an integer value.
How can I solve the problem?
Upvotes: 1
Views: 167
Reputation: 3389
There are few problems within your code :
1. First :
You have a mismatched new[]
/delete
call here. Replace delete sirul
by delete[] sirul
.
2. Second :
Inside sir::cod
, you are actually copying your object by doing
sir u=*this;
Since you are not using u
at all, you should remove this line. It is the source of your double free. At the end of the cod
function, u
will be destroyed and your internal pointer sirul
will be deleted. But since you haven't defined any copy operator, the compiler will generate it for you and you'll end up sharing a pointer across two sir
instances.
When the second instance is destroyed, sirul
is deleted again. Resulting in the error.
3. Third :
Next, in cod
, you forgot to initialize sum
to 0. That's why you have bad results.
4. Fourth :
In cod
, you are doing if (sum = 0)
. You are missing the ==
here.
Upvotes: 2