glVertexAttribPointer stride specification

An array has been defined as follow:

    float pos[6] = {
        -0.5f, -0.5f,
        0.5f, -0.5f,
        0.f, 0.5f
    };

One triangle appears as expected when glVertexAttribPointer is called with stride = 2 * sizeof(float) as follow

glEnableVertexAttribArray(0);
glVertexAttribPointer(
    0,
    2, 
    GL_FLOAT,
    GL_FALSE,
    2 * sizeof(float), 
    //5 * sizeof(float), 
    0
 );

However, when we specify stride as 5 * sizeof(float), nothing would appear on screen.
In my view, a stride = 5 indicates a 3 vertices <-.5f, -.5f>, <.5f, 0>, <.0f, .0f>

Um, why? Why is that your expectation?

The stride represents the number of bytes from the start of one value of that attribute to the start of the next. 5 floats means that the second vertex has the array index 5 (the first vertex has the index 0). The third would have the array index 10, but there is no such data. So you get an out-of-bounds read, or at least a read from an unintended portion of the buffer. Either way, you’re not reading valid data. Reading out-of-bounds from a buffer object can lead to program termination, so merely seeing nothing is about the best you can hope for.

In fact, I have tried stride = 3 and stride = 4. According to your explanation above, the 3rd vertex index in either case is out-of-bound. However, triangles do appear in both cases.

stride=3

stride=4

Out of bound reads are undefined behavior (unless you have robust buffer accesses turned on, in which case they are zero). And UB can be… anything. Including, for example… zero. Or some other value.

It’s really important to understand this: trial and error is not an effective way to learn any API or language unless that API/language is actively going to protect you from misuse of that API. C and C++ are not such languages. OpenGL is not such an API. If you misuse any of these, arbitrary things can happen. Inconsistent things can happen. Sometimes, they may even appear to “work”.

You should learn how the API works by doing things that the API says should work, not by seeing what happens when you do something the API says is broken.

1 Like

Thank you for your advice. I will take it.

One more question: as suggested by gl4/glVertexAttribPointer, stride=0 suggests attribute of tightly packed. Then, what is the difference in between stride=0 and stride=2 in this case?

The stride is specified in bytes. So I’ll assume that you meant 2*sizeof(float). If that’s the case, then there is no difference, since the attribute is two floats.

1 Like