I’m trying to overload the plus sign to concatenate two strings, but I keep getting an error.
VS 2010 gives an assertion failed message : “Expression: (L “Buffer is too small” && 0)” ; File: f:\dd\vctools\crt_bld\self_x86\crt\src\tcscat_s.inl ; Line: 42 .
What do you think is wrong with my code?
#include "stdafx.h"
class MyString{
int l; // the length of the array pointed by buf
char *buf; //pointer to a char array
public:
...
MyString(char *);
friend MyString operator+(MyString &,MyString &);
...
};
MyString::MyString(char *p)
{
buf=new char[strlen(p)+1];
strcpy_s(buf,strlen(p)+1,p);
l=strlen(p)+1;
}
MyString operator+(const MyString &a,const MyString &b)
{
MyString result("");
result.l=a.l+b.l;
delete[] result.buf;
result.buf=new char[result.l+1];
result.buf[0]='\0';
strcat_s(result.buf,result.l+1,a.buf);
strcat_s(result.buf,result.l+1,b.buf);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
MyString a("hello"),b("world"),c("");
c=a+b;
system("pause");
return 0;
}
It work now! Thank you everyone!
In operator+ the variable “MyString result” was declared on the stack and it was subsequently returned by reference, which was bad.
Then the OP was edited. The variable “result” was no longer declared on the stack, but instead allocated on the heap. However, then there was a memory leak.
The right thing to do here is to return by value and also declare “MyString result” on the stack. Also make sure you have a copy constructor. And a destructor for that matter.
You should also make your constructor takes a “const char*”.