Safely allocating dynamic arrays with new[]

831 views Asked by At

The idea is to load a Wavefront OBJ file and render it using DirectX 11.0. So far everything works, except for the actual loading of the geometry.

I allocate an array of pointers to floats to contain my vertex positions, texture coordinates and normals:

pfVertices_ = new float[nTotalVertices_ * 3];
pfNormals_ = new float[nTotalVertices_ * 3];
pfTexcoords_ = new float[nTotalVertices_ * 2];

And I release them, of course:

delete[] pfVertices_;
delete[] pfNormals_;
delete[] pfTexcoords_;

When I try to load a model containing roughly 9200 vertices, I get an access violation. I understand what the problem is, I just don't really know how to solve it. I've tried malloc() and free(), but AFAIK you can't cast a void* into a float* without asking for trouble, and it still gives me the access violation.

So, my question: Is there a safe way to allocate large arrays dynamically, or should I just put up with new's shortcomings?

EDIT: So yeah, I knew std::vector existed since the very beginning. I shied away from it because of some bad experience, and because I fear for its performance when the graphics engine becomes heavy on the GPU.

Anyway, I converted everything to std::vector, and I don't get the access violation again. BUT my geometry is invisible. I (kind of) tried if it was a problem with camera direction/position, and it wasn't. I also checked the Graphics Debugger, without any visible problems. I've had this invisible geometry problem before, but then it had to do with the rasterizer state, which can't be the case here. Does anyone have some advice about where to look for the problem?

1

There are 1 answers

6
Baum mit Augen On

Yes! You should definitely use std::vector instead of new[]! It will do all the memory management for you, and you can have range checked access with either std::vector::at or your platforms debugging facilities.

This will by itself of course not prevent access violations, but it is able to tell you with great detail (or at least more precise than what you have with new[]) where they occur, like e.g. what index you tried to access and how big the array actually is.

With those information, finding the underlying issue is usually a whole lot easier than from just a pretty useless "Segmentation fault".

Using std::vector will also make it harder for you to make some (sadly still common) mistakes like "use after free" bugs.