4

I just want to be sure.

this is my code

int * Image = (int *)malloc(sizeof(int) * m_Width/2 * m_Height);
free(Image);

if I want to use new Instead of malloc and free instead of delete. this is what i wrote

int* Image = new int[m_Width/2 * m_Height];
delete[] Image;

Is that correct?

Vivek Vermani
  • 1,934
  • 18
  • 45
Gilad
  • 6,437
  • 14
  • 61
  • 119

2 Answers2

3

Technically, it is correct. However, this is C++ we are talking about, and the C++ way to dynamically allocate an array is to use a std:vector instead:

std::vector<int> Image(m_Width/2 * m_Height);

Or:

std::vector<int> Image;
Image.resize(m_Width/2 * m_Height);

The memory will be freed automatically when the std::vector is destructed when it goes out of scope.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
2

That's correct. But if you want to gain some additional semantics without getting much OOP overhead, you can use unique_ptr:

unique_ptr<int[]> Image(new int[m_Width/2 * m_Height]);
// do something with Image...
Image.Reset(); // call it if you want to free memory manually,
               // or just leave until Image is destroyed. 
Migun
  • 83
  • 1
  • 7