heap corruption detected

hi everyone

i wrote a simple code but somehow it doesn't work.
can anyone please help me and tell me why does the content of the objects erase when it get to main.
thanks in advance.

#include <iostream>
#include <cassert>
#include <cstring>
using namespace std;

class String
{
char* pStr;
public:
String()
{
pStr = NULL;
}
String(char* str)
{
pStr = new char[strlen(str)+1];
assert(pStr!=0);
strcpy(pStr,str);
}
String &operator=(const String &ob)
{
if(&ob != this ) // check for self-assignment
{
if ( strlen(pStr) < strlen(ob.pStr) )
{ delete[] pStr;
pStr = new char [strlen(ob.pStr)+1];
assert(pStr != 0);
}
strcpy(pStr, ob.pStr);
}

return *this;
}

String(int size)
{
pStr = new char[size+1];
assert(pStr!=0);
}
~String()
{
delete[] pStr;
}
String& operator+(const String& ob)
{
String temp(pStr);
strcat(temp.pStr,ob.pStr);

return temp;
}
String& operator-()
{
String temp(strlen(pStr));
int t=0;

for(int i=strlen(pStr)-1;i>0;i--)
temp.pStr[t++] = pStr[i];

return temp;

}
String& operator*(const int rep)
{
int multiSize = strlen(pStr)*rep;
int size = strlen(pStr);
int t=0;

String temp(multiSize);

for(int i=0;i<rep;i++)
for(int j=0;j<size;j++)
temp.pStr[t++] = pStr[j];

return temp;
}
};
int main()
{
String s1("ab"),s2("bcd"),s3;
s3=s1+s2;// result "abbcd"
s3=-s3;//result dcbba
s1=s1*3; //ababab


return 0;
}
Please don't post a single question in multiple forums.

Thanks.
when I tried compiling your code I got warnings that in the operator-, operator+ and operator* fcns you were trying to return a local variable?

what compiler are you using as a matter of curiousity and did it return warnings?
warnings indicate that your code can be compiled, but this is something that will probably not work or cause problems at runtime. they are there for a reason, use them.
Topic archived. No new replies allowed.