C++ Operator Overload and String Concetanation

I designed a String class (I know there is already one)
Something like:

class String{
private:
char * str;
int size;
public:
String();
String(const String&);
String(char[]);
friend String operator+(const String&, const String&);

char* getStr() const {
    return str;
}


};    

This is the code for operator+:

String operator+(const String& str1, const String& str2){

  String s(str1); //got a copy constructor, didn't put here, and this works, this is not the problem.
  s.size=str1.size+str2.size+1; //+1 for null character at the end, not sure if necessary here, keeping the size like this is also not used anywhere...
  strcat(s.str,str2.str);
  return s;
}

I don't know why this doesn't work. Any help is appreciated...

Upvotes: 0

Views: 88

Answers (4)

Thanks. I totally missed memory allocation. Thanks everyone. This is my new operator+ function:

String operator+(const String& str1, const String& str2){
String s;
s.size=str1.size+str2.size+1;
s.str=new char[s.size];
strcat(s.str,str1.str);
strcat(s.str,str2.str);
return s;
}

Upvotes: 0

cdonat
cdonat

Reputation: 2822

I just can guess, what exactly your problem is. I see multiple issues here:

  1. You'll have to make sure, that you have allocated enough memory in s.str, before you call strcat()
  2. You should avoid fiend like the plaque. Either implement your operators as member functions or have them use the public interface.
  3. In don't know the reason, why you implement your own string class. Just don't do it. Chances are, that you won't remotely be able to make it better than std::string in any way.

I am a professional developer for roughly twenty years now and have been a hobbyist before for roughly twelve years. I have worked on many very different projects in many different companies with very different needs. I exactly had an issue that would justify a custom string class zero times. In my opinion, you should treat the standard library as part of the language and not try and reinvent the wheel, but a square one this time.

Upvotes: 1

eerorika
eerorika

Reputation: 238431

You forgot to show the code that allocates the memory pointed by s.str. However, it's easy enough to guess that you didn't allocate enough.

The solution is to allocate at least s.size long array.

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96306

Your code couldn't possibly be correct.

String s(str1);

This allocates memory, but doesn't know about the size of str2.

strcat(s.str,str2.str);

Now you append str2 to it.

You have to allocate enough space. Writing beyond allocated memory is Undefined Behaviour.

Upvotes: 1

Related Questions