views:

540

answers:

2

If for example I create an array of pixels, like so:

int *getPixels()
{
    int *pixels = new int[10];
    pixels[0] = 1;
    pixels[1] = 0;
    pixels[1] = 1;
    // etc...
}

glTexImage2D(..., getPixels());

Does glTexImage2D use that reference or copy the pixels into it's own memory?

If the answer is the former, then should I do the following?

int *p = getPixels();
glTexImage2D(..., p);

/* Just changed to delete[], because delete
 * would only delete the first element! */
delete[] p;
+4  A: 

From this quote in the man page, it sounds like glTexImage2D allocates it's own memory. This would make sense, ideally the OpenGL API would send data to be stored on the graphics card itself (if drivers/implementation/etc permitted).

In GL version 1.1 or greater, pixels may be a null pointer. In this case texture memory is allocated to accommodate a texture of width width and height height. You can then download subtextures to initialize this texture memory. The image is undefined if the user tries to apply an uninitialized portion of the texture image to a primitive.

So yea, I'd imagine there is no harm in freeing the memory once you've generated your texture.

Brian Gianforcaro
+1  A: 

Yes, after the call to geTexImage2D() returns it is safe to discard the data you passed to it. infact, if you don't do that you'll have a memory leak, like in this code:

int *getPixels()
{
    int *pixels = new int[10];
    pixels[0] = 1;
    pixels[1] = 0;
    pixels[1] = 1;
    // etc...
}

glTexImage2D(..., getPixels());

You pass the pointer to the buffer to the call but then the pointer is lost and most likely leaks. What you should do is store it and delete it aftet the call retuns:

int *pbuf = getPixels();
glTexImage2D(..., pbuf);
delete[] pbuf;

alternativly, if the texture is of a constant size, you can pass a pointer to an array that is on the stack:

{
    int buf[10];
    ...
    glTexImage2D(..., pbuf);
}

Finally, if you don't want to worry about pointers and arrays, you can use STL:

vector<int> buf;
fillPixels(buf);
getTexImage2D(..., buf.begin());
shoosh
Oops! My initial snippet used delete instead of delete[] for deleting the pixel buffer.
nbolton
actually, delete[] is what you should be using. my bad, fixed now. btw, this is exactly why you should use STL :)
shoosh
caspin