1

This is my code.. is giving me a warning saying that 'str' reference to stack memory associated with local variable 'str' returned... Also, I wanna be sure that my logic is good or if there a simpler way to way, I will really appreciate some help to learn more ways.. Thanks!

void CopyString(char *s)
{
    delete szArr;
    if (s)
    {
        szArr = new char[strlen(s)+1];
        strcpy(szArr,s);
    }
    else
    {
        szArr = new char[1];
        szArr[0]=0;
    } 
}


MyString& operator+(char *s){
    if (!s)
        return *this;
    char *tmp=new char[strlen(szArr)+strlen(s)+1];
    strcpy(tmp, szArr);
    strcat(tmp, s);
    MyString str(tmp);
    delete tmp;
    return str;
}
Richard Cook
  • 32,523
  • 5
  • 46
  • 71
JV17
  • 125
  • 2
  • 12
  • 1
    You're not using the right form of `delete` and your `operator+` should really be implemented in terms of `operator+=`. You should also not restrict a parameter that you don't change to being non-const. You're also copying `szArr`, then overwriting it with `s`. – chris Aug 08 '13 at 23:25
  • 1
    This particular probelem is solved by A.E. Drew's answer below, but a million bucks says there are a lot more problems with the code we're not seeing. – Benjamin Lindley Aug 08 '13 at 23:28

2 Answers2

2

You are returning a reference to str which is a local variable in your function.

Return a copy: MyString operator+(char *s).

A.E. Drew
  • 2,097
  • 1
  • 16
  • 24
0

Another minor fault is strcpy(tmp, s) which is not correct.Change strcpy to strcat may be right.

user1844934
  • 1
  • 1
  • 1