Apr 23, 2016 at 10:19am UTC
Hello.
My friend sent me his class for a String:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
class EString
{
char * alphanumerics;
int size;
public :
/* CONSTRUCTOR */
EString(char * mystring)
{
int i = 0;
size = strlen(mystring);
alphanumerics = new char [size + 1];
for (i = 0; i<size; i++)
alphanumerics[i] = mystring[i];
alphanumerics[i] = '\0' ;
}
/* DESTRUCTOR */
~EString()
{
cout << "I'm calling destructor for: " << this ->alphanumerics << endl;
delete [] alphanumerics;
cout << "Delete succeeded!" << endl;
size = 0;
alphanumerics = nullptr ;
}
/* ------------ GETTER ------------ */
inline int getSize() { return size; }
/* ------------OPERATORS OVERLOADING------------ */
EString& operator +(EString& other)
{
int totalSize = getSize() + other.getSize();
char * temp = new char [totalSize+1];
int i = 0;
for (i = 0; i<getSize(); i++)
temp[i] = alphanumerics[i];
for (int t = 0; t < other.getSize(); t++, i++)
{
temp[i] = other.alphanumerics[t];
}
temp[i] = '\0' ;
alphanumerics = temp;
size = totalSize;
return *this ;
}
friend ostream& operator <<(ostream& OUT, const EString& mystring)
{
OUT << mystring.alphanumerics;
return OUT;
}
};
int main()
{
{
EString nome = "A" ;
cout << nome << " size(" << nome.getSize() << ")" << endl;
EString nome2 = "B" ;
cout << nome << " size(" << nome2.getSize() << ")" << endl;
EString nome3 = nome + nome2;
cout << nome3 << " size(" << nome3.getSize() << ")" << endl;
}
system("pause" );
return 0;
}
Why isn't he able to delete the variable
nome that contains
"A" ?
He has no troubles deleting the "B", why he has deleting "A"?
This is the output in the console:
http://prntscr.com/avs4b0
And this is the error:
http://prntscr.com/avs48e
Last edited on Apr 23, 2016 at 10:25am UTC
Apr 23, 2016 at 10:56am UTC
Line 56. You're altering the char pointer inside one of the EStrings you're meant to be concatenating, and then you're returning one of the two EStrings as the whole new Estring.
The EStrings being concatenated shouldn't be changed, and you shouldn't return one of them as the new, concatenated EString. The idea is to make a whole new EString.
Last edited on Apr 23, 2016 at 11:02am UTC
Apr 23, 2016 at 11:02am UTC
What's happening in tems of computations? It's crashing why? Cause I'm assigning a char* to a char*?
Apr 23, 2016 at 11:11am UTC
It crashes because the alphanumerics pointer inside nome and nome3 point to the exact same char array, so you're calling delete on the same memory twice.
Last edited on Apr 23, 2016 at 11:13am UTC