简体   繁体   中英

strcpy/strcat strange character output

I have the following piece of code for a custom String class:

const String &String::operator+(const String &right)
{
   String temp;
   temp.length = length + right.length;
   temp.sPtr = new char [temp.length + 1];
   assert( sPtr != 0 );
   strcpy(temp.sPtr, sPtr);
   strcat(temp.sPtr, right.sPtr);
   return temp;
}

where sPtr is a char* .

But, when I execute this function on two strings, I get garbage characters as a result, like this:

 ]√Hâ«Ö“x˘" = "The date is" + " August 1, 1993

I don't have the slightest clue what is happening. I've read a couple of testimonials of people who have gotten garbage characters before the resulting string is concatenated, but I don't understand at all why the entire string would be garbage characters.

Any help would be really great. Thanks in advance!

Don't return an object by reference that is 'temporary'. Once the function ends the temp string is de-allocated, and since the string is set to temps address it becomes garbage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM