MPKenning
MPKenning

Reputation: 569

EXC_BAD_ACCESS when passing std::vector as a parameter to a function

I have a function called calculateMaxPoint() which goes through an array of vec3s to determine the maximum x, y and z values. It is used across my file multiple different time, so that it is able to go through many different arrays.

It doesn't work though. I get an EXC_BAD_ACCESS exception at runtime when the function is called. I've tried making the parameter into a pointer, and more recently I've tried using the const declaration. Neither worked.

    glm::vec3 calculateMaxPoint(std::vector<glm::vec3> & points) {
    float max[3] = {points[0].x, points[0].y, points[0].z};

    for (int i = 0; i < points.size(); i++) {
        if (points[i].x > max[0])
            max[0] = points[i].x;

        if (points[i].y > max[1])
            max[1] = points[i].y;

        if (points[i].z > max[2])
            max[2] = points[i].z;
    }

    return glm::vec3(max[0], max[1], max[2]);
    }

If any info is needed, let me know.

Upvotes: 1

Views: 517

Answers (1)

Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11934

As far as I can judge from your code, the issue could arise if the vector points that is passed as an argument is empty (contains no elements). In that case referencing the element with index zero that you are doing on the first line is invalid. What you should do is add a line that checks if the vector is empty and handle that scenario. The snippet below returns a vector with all zero values:

if (points.size() == 0)
{
    // In this example return a vector with 0 values
    return glm::vec3(0, 0, 0);
}

You can modify this code as to your needs - return a vector with different values or possibly throw and exception.

Upvotes: 2

Related Questions