Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ object created with new keyword does not render; object created on the stack does

Tags:

c++

opengl

Edit: I have stripped out all texturing and normal mapping but the problem still remains

I am trying to draw a chunk of terrain on the screen. The render function looks like this:

void TerrainChunk::Render()
{
   std::cout << "Render Me!\n";
   glColor3f(0.5f, 0.5f, 0.5f)
   glDisable(GL_LIGHTING);
   for(int x = 1; x < kChunkSize - 1; x++)
   {
      for(int z = 1; z < kChunkSize - 1; z++)
      {
         std::cout << height_map_[x][z] << " ";
         glBegin(GL_TRIANGLE_STRIP);
            glVertex3f(x, height_map_[x][z], z);
            glVertex3f(x+1, height_map_[x+1][z], z);       
            glVertex3f(x, height_map_[x][z+1], z+1);
            glVertex3f(x+1, height_map_[x+1][z+1], z+1);
         glEnd();
      }
      std::cout << std::endl;
   }
   glEnable(GL_LIGHTING);
}

When the object is created on the stack

TerrainChunk chunk("chunk1.png", "grass.png");
chunk.Init();

it renders perfectly.

When I create it with new

TerrainChunk *chunk = new TerrainChunk("chunk1.png", "grass.png");
chunk->Init();

nothing shows up. In both cases, Render is being called and the correct heightmap is being printed out. I would expect both of these cases to behave identically.

Edit: Here is the Init() code as requested. All it does is load the height map which I've already verified is correct on each call to Render().

void TerrainChunk::Init()
{
   std::cout << height_file_ << ", " << texture_file_ << std::endl;

   //Load height map
   SDL_Surface *temp = IMG_Load(height_file_.c_str());
   if(!temp)
   {
      printf("Failed to load chunk.\n");
      exit(-1);
   }
   Uint32 *pixels = (Uint32 *)temp->pixels;
   for(int z = 0; z < kChunkSize; z++)
   {
      for(int x = 0; x < kChunkSize; x++)
      {
         Uint8 r, g, b;
         SDL_GetRGB(pixels[x + z * temp->w], temp->format, &r, &g, &b);
         height_map_[x][z] = g / 12;
      }
   }
}
like image 483
Timulus Avatar asked Nov 01 '12 15:11

Timulus


1 Answers

When the same object works when created on the stack, but doesn't when created in the heap, or vice versa, more often than not it's because a member is left ununitialized. Heap allocations are zero-initialized, and stack allocations aren't. I recommend running your program under valgrind, it will most likely tell you what's wrong.

like image 157
Alexey Feldgendler Avatar answered Oct 23 '22 06:10

Alexey Feldgendler