Reputation: 7367
I am trying to use glReadPixels
to extract the image data via the following code:
std::array<unsigned char, 3 * height * width> data;
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, data.data());
The image is perfect when the width is a multiple of 4 (height seems to be arbitrary). When it is not, however, I get the runtime error:
*** stack smashing detected ***: <unknown> terminated
So for example, the following (width,height) pairs work fine:
(20,20),(20,21),(20,22),(20,23),(20,24)
(24,20),(24,21),(24,22),(24,23),(24,24)
The following yield "stack smashing" errors:
(21,20),(22,20),(23,20)
I would guess that there is some padding going on, but I don't see any mention of it on the OpenGL website:
https://www.khronos.org/registry/OpenGL-Refpages/gl2.1/xhtml/glReadPixels.xml
Could somebody please point me to some documentation explaining how much space I should allocate, and what the padding looks like?
Upvotes: 3
Views: 242
Reputation: 22170
By default, the alignment for read operations GL_PACK_ALIGNMENT
is set to 4 bytes. This means, that every row has to start at an address with this alignment. Since you are reading 3 bytes per pixel, you're needing more memory than expected if (3 * width) % 4 != 0
.
You can either allocate the required amount of memory, or you can force a different alignment by calling
glPixelStore(GL_PACK_ALIGNMENT, desired_alignment);
As @dave noted, only 1, 2, 4 or 8 is allowed as alignment.
Upvotes: 7