EXC_BAD_ACCESS with vector<ofColor>

Hi, I am trying to use vector<ofColor>, but I got EXC_BAD_ACCESS. Xcode says Build Succeeded.
How do I use vector<ofColor> with setHsb properly?
Why does this error occur?

This is where EXC_BAD_ACCESS showed up.

This is my code:

ofApp.h:

vector<ofColor> colors;

ofApp.cpp

void ofApp::setup(){
    ofColor color;
    for(int i = 0; i < colors.size(); i++){
        color.setHsb(i * 50, 222, 255);
        colors.push_back(color);
    }
}

void ofApp::draw(){
    ofBackground(250);
    ofSetColor(colors[0]);
    ofDrawCircle(300, 300, 100);
}

Thank you!

Hi.

The vector <ofColor> colors; has no elements added to it because your for loop is using the size of the colors vector ( which is 0 ) as the number of times to loop.

That is why you are getting a memory error when trying to access colors[0].

if you wanted say 10 elements.

I would either do this:

void ofApp::setup(){
    ofColor color;
    int numColors = 10; 
    for(int i = 0; i < numColors; i++){
        color.setHsb(i * 50, 222, 255);
        colors.push_back(color);
    }
}

or you could assign the vector to be 10 elements and then just treat like an array.

void ofApp::setup(){
    ofColor color;
    colors.resize(10);  
    for(int i = 0; i < colors.size(); i++){
        color.setHsb(i * 50, 222, 255);
        colors[i] = color;
    }
}

Hope that helps!
Theo

1 Like

Hi!

It works. Thank you so much!!