Reputation: 976
I'm making an own class String in C++.
I have a problem with this:
class String {
char* arr;
int len;
friend ostream& operator << (ostream& s, const String& c) {
return s << c.arr;
}
Public:
String() {
arr = NULL;
len = 0;
}
String(const char* name) {
*arr = *name;
}
}
In main I have this:
String *s = new String("abcde");
cout << *s << endl;
The problem is that the compilator shows me this:
Bus error : 10
I'm working on a mac, using the terminal with g++.
How can I solve this problem?
Thanks in advance.
Upvotes: 2
Views: 140
Reputation: 126442
This:
String(const char* name) {
*arr = *name;
// ^^^^
}
Is dereferencing an uninitialized pointer, thus giving you undefined behavior. I guess what you actually want to do is something like this:
#include <cstring> // For strlen() and strcpy()
String(const char* name) {
len = strlen(name);
arr = new char[len + 1];
strcpy(arr, name);
}
Also, do not forget to provide a destructor for cleanup, a copy constructor, and a copy assignment operator - and if working in C++11, also a move constructor and a move assignment operator.
Upvotes: 6