-4

My code is something like this in C++

MyObject* someObject;

void makeArray(int sizeArray)
{
    someObject = (MyObject*) malloc(sizeof(MyObject) * sizeArray);
}

Now this compiles without any errors or warnings, but when I run the program it instantly crashes. I have also tried to hardcode the array in, and I do have enough memory for it. I haven't used malloc too much, so I probably have something coded wrong, but if that's the problem, what is it?

2 Answers2

3

Memory allocation is not construction

You should not use malloc when you are creating objects that have a non-trivial constructor, mainly because malloc will not call any constructor; it will merely allocate memory, nothing more.

In C++, you use operator new to allocate memory and construct the object:

MyObject* someObject;

void makeArray(int sizeArray) {
    someObject = new MyObject[sizeArray];
}

Note: For every new you shall have a matching delete, please remember to use delete[] someObject when you are done.


Recommended solutions

The C++ way of doing things is to use std::vector which will handle memory management, and object construction/destruction for you:

std::vector<MyObject> vec (sizeArray); // create a vector with `sizeArray` elements

If you "must" use pointers please don't use raw-pointers, instead you should use smart-pointers if those are available under your implementation:

Community
  • 1
  • 1
Filip Roséen - refp
  • 62,493
  • 20
  • 150
  • 196
1

Why are you using malloc in C++? new is what you should be using

i.e.

someObject = new MyObject[sizeArray];

then use delete[] to delete it!

Ed Heal
  • 59,252
  • 17
  • 87
  • 127