Search code examples
c++openglglteximage2d

Returning result of stbi_load function and using it for glTexImage2D causes memory violation


I've a problem with the stbi library and I thought, maybe you have an idea why this isn't working. I have declared a function like this:

bool LoadTextureFile(std::string file, unsigned char ** pixel_data, int * width, int * height, int * n);

In this function I get the result of stbi_load directly saved in the *pixel_data variable:

*pixel_data = stbi_load(file.c_str(), width, height, n, 0);
// Do some more stuff till return
return true;

So, now my pixel_data pointer points to the memory of the result of stbi_load. Now I wanna use this result with the glTexImage2D method in my previous function. This function calls the LoadTextureFile method before calling the glTexImage2D method of OpenGL like this:

bool LoadTexture(...)
{
  int tex_width, tex_height, tex_n;
  unsigned char * pixel_data    = NULL;
  LoadTextureFile(filename, &pixel_data, &tex_width, &tex_height, &tex_n);
  // Do something special ...
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, tex_width, tex_height, 0, GL_RGB, GL_UNSIGNED_BYTE, &pixel_data);
  stbi_image_free(&pixel_data);
  // ...
}

But if I do it like that, then I get a memory violation message at the point of calling the glTexImage2D. If I move this whole magic into the LoadTextureFile, after loading a new texture file with stbi_load, then it works:

bool LoadTextureFile(std::string file, unsigned char ** pixel_data, int * width, int * height, int * n)
{
  unsigned char * = = stbi_load(file.c_str(), width, height, n, 0);
  // Do some magic ...
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 80, 80, 0, GL_RGB, GL_UNSIGNED_BYTE, pixel_data); 
  stbi_image_free(pixel_data);
  return true;
}

Can someone tell me why I get this message and how to solve this problem?

I guess, it is a matter of keep the reserved memory safe, but I'm not really sure, how to solve it. I tried this in a simple console application before, and there it works.

Thank you for your help!


Solution

  • This:

    unsigned char * pixel_data    = NULL;
    [...]
    glTexImage2D(..., &pixel_data);
    

    is certainly not what you want. You are using the address of the pionter to your pixel data, not the value of the pointer, so you are basically telling the GL to use some random segment of your stack memory as source for the texture. It should be just

    glTexImage2D(..., pixel_data);
    

    In your second variant, what actually happens is unclear since the line

    unsigned char * = = stbi_load(file.c_str(), width, height, n, 0);
    

    just doesn't make sense and will never compile. So I assume it is copy and paste error when writing the question. But it is hard to guess what your real code would do.