Answer the question
In order to leave comments, you need to log in
C++ template class. Help! Why does segfault crash when trying to push std::string?
help!!! I don’t know what to do anymore, I
write like std::vector, but
let’s say I allocate 100 bytes, if I create a list with ints, then everything is OK, but if with std::string I get a segmentation fault when adding . I seem to be doing everything right, memory is allocated, I tried everything I knew and googled
ArrayList<int> *list = new ArrayList<int>();
list->push_back(5); // ok
ArrayList<string> *list = new ArrayList<string>();
list->push_back("hello"); // segfault
template <class Type>
class ArrayList {
private:
Type *array;
public:
ArrayList() : {
array = (Type*) malloc(100);
}
~ArrayList() {
free(array);
}
void push_back(Type elem) {
array[0] = elem;
}
const Type& operator[](size_t index) const {
return array[index];
}
};
Answer the question
In order to leave comments, you need to log in
array[0] = element;
it means calling
array[0].operator=(elem);
in the "string::operator=()" function and crashes, because array[0] contains garbage, because no constructor was called for it (for array[0])
Instead of
array = (Type*) malloc(100 );
probably meant
array = new Type[100];
and the place is free, then delete[]array
Well, let's start with the fact that string in C++ is a std::string object .
Type *array is a pointer to an object of type string.
You allocate 100 bytes of memory and convert a pointer to that memory into a pointer to an object of type std::string.
And then you try to write an object into these 100 bytes, which, obviously, has a size of more than 100 bytes.
Try adding more than 25 int elements or more than 12 double elements - get the same segfault
In general, such things are usually done as a linked list
Found a simple implementation .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question