Question

I am trying to draw a quad using a VBO, here is the full code but I'll post the code step by step: here is how I initialize the buffer:

data= vector<GLfloat> {  // Global variable vector<GLfloat> data;
// Viewport: glViewport(0,0,width,height);
    width/2+20,height/2+20,0.0,
    width/2+20,height/2-20,0.0,
    width/2-20, height/2-20,0.0,
    width/2-20, height/2+20,0.0
};
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, 12*sizeof(GLfloat), data.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);

Then in the display function I try to draw the quad (I use double buffering):

glClearColor(1.0, 1.0, 1.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glColor3f(1, 0, 0);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, data.data());
glDrawArrays(GL_QUADS, 0, 4); // Here I get segmentation fault
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);

glutSwapBuffers();

I get segmentation fault at the line where I call glDrawArrays, I also tried to get the OpenGL errors with glGetError(), but there's no error (it returns zero).

Was it helpful?

Solution

You are using the following line in the initialization:

glBufferData(GL_ARRAY_BUFFER, 12*sizeof(GLfloat), data.data(), GL_STATIC_DRAW);

When drawing you set up your attrib pointers like this:

glVertexPointer(3, GL_FLOAT, 0, data.data());

I suspect that data.data() is the same in both cases - making this an error. When an ARRAY_BUFFER is bound, the pointer argument of the various gl*Pointer() functions does not refer to a client memory address, but to a byte offset in the VBOs. When drawing, the GL will try to fetch this data which is very likely to be way out of bounds of the buffer object - hence the crash. You probably meant:

glVertexPointer(3, GL_FLOAT, 0, NULL);

Note that the original VBO extension has this often-used macro in the examples section:

#define BUFFER_OFFSET(i) ((char *)NULL + (i))

Using that, you can conveniently hide those ugly pointer arithmetic nicely and can address byte offsets in your buffer: glVertexPointer(3, GL_FLOAT, 0, BUFFER_OFFSET(0));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top