Hi. I’ve been trying to draw a series of triangles to the screen. I generate buffers, bind them correctly, and buffer the arrays of floats using glBufferData. If I use arrays of data created with stack memory, it works fine. The problem occurs when I create dynamically allocated arrays from the heap and pass them to OpenGL. I wrote a test function that emulates exactly what I’m trying to do elsewhere which highlights the problem.
Here’s the code that works fine:
void testFunction() {
GLuint vertexBufferId, indexBufferId;
int triangleCount = 3;
float newPositions[] = {
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, 0.5f
};
GLushort vertexIndices[] = {
0, 1, 2,
2, 1, 3,
0, 1, 4
};
glGenBuffers(1, &vertexBufferId);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(newPositions), newPositions, GL_STATIC_DRAW);
glGenBuffers(1, &indexBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertexIndices), vertexIndices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawElements(GL_TRIANGLES, triangleCount * 3, GL_UNSIGNED_SHORT, 0);
}
When I change the data to use dynamically allocated memory, I get a black screen instead of the triangles which were drawn before.
void testFunction() {
GLuint vertexBufferId, indexBufferId, colourBufferId;
int triangleCount = 3;
float* newPositions = new float[15]{
-0.5f, 0.5f, -0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, 0.5f
};
GLushort* vertexIndices = new GLushort[9] {
0, 1, 2,
2, 1, 3,
0, 1, 4
};
glGenBuffers(1, &vertexBufferId);
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferId);
glBufferData(GL_ARRAY_BUFFER, sizeof(newPositions), newPositions, GL_STATIC_DRAW);
glGenBuffers(1, &indexBufferId);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferId);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertexIndices), vertexIndices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glDrawElements(GL_TRIANGLES, triangleCount * 3, GL_UNSIGNED_SHORT, 0);
delete[] vertexIndices;
delete[] newPositions;
}
I’m still quite new to OpenGL, so if I need to approach it differently with heap memory then please let me know. Thanks for your help.