I'm getting the segmentation fault in the following code. Could you please help me to figure it out? In the following code, it prints "ok here". Once it deallocates the memory, it shows the segmentation fault. But why ? any solution ?
Any help on this will be appreciated.
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
class Cube
{
public:
char *str;
Cube(int len)
{
str = new char[len+1];
}
Cube(const Cube &c)
{
str = new char[strlen(c.str) + 1];
strcpy(str, c.str);
}
~Cube()
{
delete [] str;
}
};
void foo(vector <Cube> *vec)
{
for (int i = 0; i < 10; i++)
{
char in [] = "hello !!";
Cube *c = new Cube(strlen(in)+1);
strcpy(c->str, in);
vec->push_back(*c);
cout << "ok here" << endl;
delete [] c;
}
}
int main()
{
vector <Cube> vec;
foo(&vec);
return 0;
}