Archived

This topic is now archived and is closed to further replies.

Jonus

Question about memory leaks ...

Recommended Posts

When i do something like that:
int * temp = 10; 
must i call
delete temp; 
to prevent that memory leak? I mean do i get one when i don't delete it? Edited by - Jonus on February 21, 2002 4:56:39 PM

Share this post


Link to post
Share on other sites
That example you gave won''t compile under any normal compiler. Perhaps you meant:

int * temp = new int(10); // *temp now equals 10

If you forget to delete the memory afterwards, then yes, it''s a memory leak.

Share this post


Link to post
Share on other sites
no. you only call delete when you have called new

i.e.

int *tmp = new int[20];
..
..
delete [] tmp; //deletes the array of dynamically allocated ints

deleting it frees that memory back up so it can be used again, by not doing so the computer thinks its still in use after the program has finished running and nothing else will use it(the memory).... if that keeps happening you'll eventually run out of memory and need to reboot.

edit: wah- beat to it

Edited by - Bezzant on February 21, 2002 5:09:01 PM

Edited by - Bezzant on February 21, 2002 5:09:43 PM

Share this post


Link to post
Share on other sites
Declaring int* temp = 10 is not a good idea. int* is a pointer to an int, not an actual int. You need to do this:

void myfunction() {

int* temp;

temp = new int;
*temp = 10;

delete temp;

}

A memory leap occurs would occur if you didn''t call delete temp before the function ended. temp would go out of scope, so you''d have no way to access the memory allocated by new. You would now have a block of allocated memory which can no longer be written to or read from. This is what''s called a memory leak. Imagine if this was not just one int, but a huge array, and you''ll see why this can become a major problem.

Share this post


Link to post
Share on other sites
Whoa! Good thing I read this post I forgot all about deleting all my dynamic memory. Hehehe.

Jeff D


Suffered seven plagues, but refused to let the slaves go free. ~ Ross Atherton

Share this post


Link to post
Share on other sites
Is a class''s destructor called whenever the object leaves scope then? Or do you have to "delete" your objects?

"I''''m not evil... I just use the power of good in evil ways."

Share this post


Link to post
Share on other sites
Tac-Tics: Yes. The destructor is called when an object on the stack leaves scope. You need only delete objects created dynamically (with new).

"Don''t be afraid to dream, for out of such fragile things come miracles."

Share this post


Link to post
Share on other sites