I would like to draw a triangle with a C++ program. I compiled the program with g++, with the '-Wall' flags and it compiles with no warnings. However, I get a segmentation fault coming from the function glGenBuffers(1, &m_VertexBuffer);
. I have tried replacing the type declaration from uint32_t
to GLuint
, but the issue persists.
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
int main()
{
if (!glfwInit())
{
std::cout << "Failed glfwInit()" << std::endl;
return 1;
}
GLFWwindow* window = glfwCreateWindow(600,600, "triangle", NULL, NULL);
if (!window)
{
glfwTerminate();
std::cout << "Failed to create window" << std::endl;
return 1;
}
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
glfwTerminate();
std::cout << "Failed gladLoadGLLoader(...)" << std::endl;
return 1;
}
float vertices[] =
{
-.5f, -.5f, 0.f,
.5f, .5f, 0.f,
0.f, -.5f, 0.f
}; //triangle
uint32_t m_VertexBuffer;
std::cout << "Generating buffer object from vertex array..." << std::endl;
glGenBuffers(1, &m_VertexBuffer);
std::cout << "Done." << std::endl;
glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (void *) 0);
glEnableVertexAttribArray(0);
glViewport(0, 0, 600, 600);
while(!glfwWindowShouldClose(window))
{
glClear(GL_COLOR_BUFFER_BIT);
glDrawArrays(GL_TRIANGLES, 0, 3);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
}
When I execute the binary, here is the output of the terminal:
Generating buffer object from vertex array...
Segmentation fault
When I use gdb, here is the output (line 40 corresponds to the glGenBuffers(1, &m_VertexBuffer);
) line.
Starting program: /home/jiageng/tri/build/tri
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Program received signal SIGSEGV, Segmentation fault.
0x0000000000000000 in ?? ()
(gdb) backtrace
#0 0x0000000000000000 in ?? ()
#1 0x0000555555557d8b in main () at /home/jiageng/tri/main.cpp:40
I see a black window called "triangle", but nothing is shown on this window.
Additional details: The code I am showing is adapted from a tutorial on youtube I was following. The working code of this tutorial is here (https://github.com/codetechandtutorials/tri/blob/main/main.cpp). The only things I have changed are replacing one-letter variable names with more descriptive terms, and added breakpoints and verbose statements.
I am on Windows Subsystem for Linux 2, and have verified that X11-port forwarding works properly so I can run GUI applications through VcXSrv.