Luke Luke - 1 year ago 80
C++ Question

Error when trying to use glDrawArrays in C++

I am trying to draw a simple rectangle in my game but I keep running into the following break:
enter image description here

Here is the code in my Sprite.cpp where I bind and render things.

void Sprite::init(float x, float y, float width, float height){

this->x = x;
this->y = y;
this->width = width;
this->height = height;

if(vbo == 0)
glGenBuffers(1, &vbo);

Vertex vertex[6];

vertex[0].setPosition(x, y);
vertex[0].setUV(0, 0);

vertex[1].setPosition(x, y + height);
vertex[1].setUV(0, 1);

vertex[2].setPosition(x + width, y + height);
vertex[2].setUV(1, 1);

vertex[3].setPosition(x, y);
vertex[3].setUV(0, 0);

vertex[4].setPosition(x + width, y);
vertex[4].setUV(1, 0);

vertex[5].setPosition(x + width, y + height);
vertex[5].setUV(1, 1);

for (int i = 0; i < 6; i++)
vertex[i].setColor(0.0, 0.0, 1.0, 1.0);

glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(vbo, sizeof(vertex), vertex, GL_DYNAMIC_DRAW);

glBindBuffer(GL_ARRAY_BUFFER, 0);


void Sprite::render(){

glBindBuffer(GL_ARRAY_BUFFER, vbo);


glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, position));
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(Vertex), (void*)offsetof(Vertex, color));
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, uv));

glDrawArrays(GL_TRIANGLES, 0, 6);


glBindBuffer(GL_ARRAY_BUFFER, 0);


If i comment out the line "glDrawArrays(GL_TRIANGLES, 0, 6)" Then the program will run perfectly fine. Here is my Vertex struct just for additional information:

#pragma once
#include <GL\glew.h>

struct Position {

float x, y;


struct UV{

float u, v;


struct Color {

GLubyte r, g, b, a;

struct Vertex {

Position position;

Color color;

UV uv;

void setUV(float u, float v) {
uv.u = u;
uv.v = v;

void setColor(GLubyte r, GLubyte g, GLubyte b, GLubyte a) {
color.r = r;
color.g = g;
color.b = b;
color.a = a;

void setPosition(float x, float y) {
position.x = x;
position.y = y;

I just seriously have no idea why this is happening. I have heard this error has to do with de-referencing some null pointer or something. I just don't know how to tackle this problem. Any help is extremely appreciated.

Answer Source

this: glBufferData(vbo, sizeof(vertex), vertex, GL_DYNAMIC_DRAW);

should be :glBufferData(GL_ARRAY_BUFFER, sizeof(vertex), vertex, GL_STATIC_DRAW);

because the first argument specifies the how your array should be used.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download