🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

pointer and memory...

Started by
2 comments, last by FireViper 18 years ago
Im working on my game engine, and wanted to delete unnecessary to make the engine run faster. This is the code Im using:


class vector
{
 public:
 float x, z, y;     
};

 vector *vec;
 vec = new vector;
 float a = 5;
 float b = 3;
 
 vec->x = a;
 vec->y = b;
 printf("x: %f y:%f \n", vec->x, vec->y); 
 delete vec;
 printf("x: %f y:%f \n", vec->x, vec->y); 


but this is the output: -------------------------- x:5.0000000 y:3.0000000 x:0.0000000 y:3.0000000 -------------------------- it deletes the x variable, but dosen't delete y. Does anyone know what I'm doing wrong?
Advertisement
 // vec exists here, so prints the expected values. // printf("x: %f y:%f \n", vec->x, vec->y);  // after deleting vec, vec no longer exists delete vec; // the result of this line is now undefined since vec // no longer exists. The results you are seeing is due to // the fact that vec is now pointing to some random memory // location.  printf("x: %f y:%f \n", vec->x, vec->y); // typically, after deleting memory from a pointer,  // set it to NULL which will later alow you to check  // to see if the pointer is valid vec=0; if(vec)   printf("x: %f y:%f \n", vec->x, vec->y);

The proper way to delete a pointer is by filling it with garbage data, deleting it, and then setting it to NULL. This way its virtually shredded from memory.
thanks for clearing that up for me.

This topic is closed to new replies.

Advertisement