I have a simple c++ phonebook project, and I'm no allowed to use std::vector. So i decided i create one for myself. And I'd like to ask a little help about my push_back function.
So this is in the vector.h:
class Vector{
int siz; //size
std::string* elem; //elements
public:
Vector(): siz(0){}
int getSize()const;
void pushBack(std::string const&);
std::string operator[](int) const;
Vector& operator=(const Vector&);
};
And this is my push_back function:
void Vector::pushBack(std::string const& s){
std::string* temp = new std::string[siz + 1];
for(int i = 0; i < siz; i++)
temp[i] = elem[i];
temp[siz] = s;
// delete[] elem; // The debugger points here
this->elem = temp;
this->siz += 1;
}
This is where I use the push_back function:
const Vector read(){
Vector v;
std::ifstream file;
file.open("data.txt", std::ios::in);
int db = 10 * linecounter();
std::string temp;
for(int i = 0; i < db; i++)
{
if(i % 10 == 9 && i != 0){
getline(file, temp); // the last data in the line after that ther is a \n
v.pushBack(temp);
}
else{
getline(file, temp, ';'); // read in the temp till the ;
v.pushBack(temp); // The debugger points here
}
}
return v;
}
And my problen is, when I dont't use delete[] elem;
It's going to create some memory leak. When I use, the program crashes immediately.