I'm trying to replace operator new and delete with malloc and free (I got reasons for that). The problem is shown in code below:
std::string *temp = (std::string *)malloc(sizeof(std::string) * 2); // allocate space for two string objects.
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
printf("%s\n", temp[i].c_str());
}
free(temp);
return 0; // causes SIGSEGV.
however..
std::string *temp = new std::string[2];
temp[0] = "hello!";
temp[1] = "world!";
for(int i = 0; i < 2; i++)
{
printf("%s\n", temp[i].c_str());
}
delete [] temp;
return 0; // works fine
Why? and could anyone suggest me what is a right way to replace these operators with malloc and free?
Regards.
EDIT: this is just example, I'm not using standard C++ library.
EDIT: what about something like this?
class myclass
{
public:
myclass()
{
this->number = 0;
}
myclass(const myclass &other)
{
this->number = other.get_number();
}
~myclass()
{
this->number = 0;
}
int get_number() const
{
return this->number;
}
void set_number(int num)
{
this->number = num;
}
private:
int number;
};
int main(int argc, char *argv[])
{
myclass m1, m2;
m1.set_number(5);
m2.set_number(3);
myclass *pmyclass = (myclass *)malloc(sizeof(myclass) * 2);
pmyclass[0] = myclass(m1);
pmyclass[1] = myclass(m2);
for(int i = 0; i < 2; i++)
{
printf("%d\n", pmyclass[i].get_number());
pmyclass[i].myclass::~myclass();
}
free(pmyclass);
return 0;
}