Dan
Dan

Reputation: 51

Heap corruption when using make_shared

I have a class with private member variable

shared_ptr<short> m_p_data;

I get heap corruption when I use this constructor:

Volume2D(const int dimX, const int dimY) :m_dimX{ dimX }, m_dimY{ dimY }, m_p_data{ make_shared<short>(dimX*dimY) } {
}

but there is no heap corruption if I do this instead:

Volume2D(const int dimX, const int dimY) :m_dimX(dimX), m_dimY(dimY) {
  m_p_data.reset(new short[dimX*dimY]);
}

To be more specific, here is the code that corrupts the heap:

Volume2D vol(10, 1);
for (auto i = 0; i < 10; ++i) {
    vol(i, 0) = i;
    cout << "value = " << vol(i, 0) << endl;
}
return 0;

Upvotes: 1

Views: 510

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

Both versions of your code are problematic.

The first version,

make_shared<short>(dimX*dimY)

creates a single heap-allocated short with the value dimX*dimY. It is apparent from the rest of your question, that your code later treats this logically as an array of dimension dimX*dimY, which is exactly what's causing the heap corruption (you only allocated a single short, but you're treating it like many).

The second version has the opposite problem. You're allocating dimX*dimY shorts, but, as far as your shared_ptr, it doesn't know that. So it doesn't have your heap corruption, but the shared_ptr destructor calls delete, not delete[] (even though you allocated with new[], not new).


For this case, its' unclear why you need a shared_ptr to begin with. Why not use std::vector<short>, or std::vector<std::vector<short>>?

Upvotes: 1

Related Questions