Question

Le message:

terminate called after throwing an instance of 'std::bad_alloc'
what():  std::bad_alloc

Je regardais les backtrace gdb et c'est la méthode la plus faible de niveau là que je me suis mis en œuvre:

/*
 * get an array of vec3s, which will be used for rendering the image
 */
vec3 *MarchingCubes::getVertexNormalArray(){
    // Used the same array size technique as getVertexArray: we want indices to match     up
    vec3 *array = new vec3[this->meshPoints.getNumFaces() * 3]; //3 vertices per face

    int j=0;
    for (unsigned int i=0; i < (this->meshPoints.getNumFaces() * 3); i++) {
        realVec normal = this->meshPoints.getNormalForVertex(i);
 //     PCReal* iter = normal.begin();

        if (normal.size() >= 3) {
            array[j++] = vec3(normal[0], normal[1], normal[2]);
        }
        cout << i << " ";
    }

    return array;
}

L'instruction Cout que vous voyez ci-dessus indique qu'elle se termine après 7000+ itérations. La fonction ci-dessus est appelée une seule fois à la fin de ma demande. J'appelle une fonction très similaire avant d'appeler ce qui précède, qui ne posent pas de problèmes.

Était-ce utile?

La solution 2

My problem turned out to be that this->meshPoints.getNormalForVertex(i) accesses an array (or vector, I can't remember) whose length is less than this->meshPoints.getNumFaces() * 3. So it was accessing out of bounds.

Autres conseils

(moving/expanding from the comments)

Since you are allocating a new array every time without deallocating it, you have a massive memory leak, i.e. you continue to ask memory to the system without ever giving it back. Eventually the space on the heap finishes, and at the next allocation all you get is a std::bad_alloc exception.

The "C-style" solution would be to remember to deallocate such memory when you don't need it anymore (with delete[]), but, this is (1) error-prone (think e.g. if you have multiple return paths inside a function) and (2) potentially exception-unsafe (every instruction becomes a potential return path if you have exceptions!). Thus, this way should be avoided.

The idiomatic C++ solution is to use either smart pointers - small objects that encapsulate the pointer and deallocate the associated memory when they are destroyed - or standard containers, that do more or less the same thing but with copy semantics and some more bells and whistles (including storing the size of the array inside them).

I got this error trying to allocate a negative length array:

double myArray = new double[-9000];

Just in case it helps anyone.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top