Access Violation reading location glTexImage2D()

#1

I have a class to load textures. It works fine for the first try, but the second time I try to create a texture, it gives me an access violation exception at glTexImage2d().

Code:

Texture::Texture(const char* textureFile)
{
	glGenTextures(1, &textureID);
	glBindTexture(GL_TEXTURE_2D, textureID);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	int width, height, nrChannels;

	unsigned char* data = stbi_load(textureFile, &width, &height, &nrChannels, 0);
	if (data)
	{
        //exception occurs here
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
		glGenerateMipmap(GL_TEXTURE_2D);
	}
	else
	{
		printf("Could not load image %s!\n", textureFile);
	}
	stbi_image_free(data);
}
#2

Either set the last parameter to STBI_rgb_alpha (=4) or check the value of nrChannels and set the format parameter of glTexImage2D accordingly.

#3

Thanks! It worked after I set that to STBI_rgb_alpha.