heap corruption detected

can someone please tell me what's wrong with this code...
i don't understand why the objects's content erased before it gets to main.
thanks


#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;
}
g++ f.cpp
f.cpp: In member function `String& String::operator+(const String&)':
f.cpp:46: warning: reference to local variable `temp' returned
f.cpp: In member function `String& String::operator-()':
f.cpp:53: warning: reference to local variable `temp' returned
f.cpp: In member function `String& String::operator*(int)':
f.cpp:68: warning: reference to local variable `temp' returned

That can never be good.

EDIT: those methods need to return by value.
Last edited on
Topic archived. No new replies allowed.