c++ - Trying to calculate ASCII code sum of my "sir" (string) class -
#include <iostream> #include <string.h> using namespace std; class sir{ int lung; //sir lenght char* sirul; //pointer 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 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 sir-----------------\n"; sir s("un sir meserias"); char c=s[1]; cout<<c<<"\n"; cout<<s.cod(); }
when i'm executing program error says "double free or corruption", don't understand causes error. appears after i'm trying calculate ascii code sum of sir(string) cod
method, should return integer value.
how can solve problem?
there few problems within code :
1. first :
you have mismatched new[]
/delete
call here. replace delete sirul
delete[] sirul
.
2. second :
inside sir::cod
, copying object doing
sir u=*this;
since not using u
@ all, should remove line. source of double free. @ end of cod
function, u
destroyed , internal pointer sirul
deleted. since haven't defined copy operator, compiler generate , you'll end sharing pointer across 2 sir
instances. when second instance destroyed, sirul
deleted again. resulting in error.
3. third :
next, in cod
, forgot initialize sum
0. that's why have bad results.
4. fourth :
in cod
, doing if (sum = 0)
. missing ==
here.
Comments
Post a Comment