c++opengltexture2dfreeglutdevil

Segmentation fault loading texture with Devil into OpenGL


I am attempting to load a texture into OpenGL using Devil, and i am having a segmentation fault upon the calling of this constructor

Sprite::Sprite(const char *path){

    ILuint tex = 0;

    ilutEnable(ILUT_OPENGL_CONV);
    ilGenImages(1, &tex);
    ilBindImage(tex);
    ilLoadImage(path);
    ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
    width  = (GLuint*)ilGetInteger(IL_IMAGE_WIDTH);
    height = (GLuint*)ilGetInteger(IL_IMAGE_HEIGHT);

    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGBA,
                 width,
                 height,
                 0,
                 GL_RGBA,
                 GL_UNSIGNED_BYTE,
                 &tex);

    ilBindImage(0);
    ilDeleteImages(1, &tex);
    ilutDisable(ILUT_OPENGL_CONV);

}

and texture is a protected member

GLuint texture;

As soon as this constructor is called i recieve a segfault error and it exits and I am using freeglut, gl, il, ilu, and ilut. any help would be appreciated

Edit:

I also decided to take a different approach and use

texture = ilutGLLoadImage(path)

function to just load it directly into the gl texture because I located the segfault coming from

ilLoadImage(path)

but the compiler tells me that ilutGLLoadImage() is not declared in this scope, and i have IL/il.h IL/ilu.h and IL/ilut.h all included and initialized


Solution

  • I never used DevIL, but glTexImage2D wants pointer to pixel data as the last argument and you pass pointer to local variable tex there instead, which is allocated on stack and does not contain expected information. So glTexImage2D reads through your stack and eventually attempts to access memory it was not supposed to access and you get segmentation fault.

    I guess you'd want to use ilGetData() instead.