What are memory leaks?

Please reference title. I've been hearing a lot about this but I'm just a beginner...
It's when you allocate memory but don't release it.

1
2
3
4
5
6
7
8
9
#include <iostream>

int main( int argc, char* argv[] )
{
   int *myInt= new int(5); // Memory allocated here
   std::cout << "myInt is " << *myInt << std::endl;

   return 0;
}


What should be done...
1
2
3
4
5
6
7
8
9
10
#include <iostream>

int main( int argc, char* argv[] )
{
   int *myInt= new int(5); // Memory allocated here
   std::cout << "myInt is " << *myInt << std::endl;
   delete myInt;  // Memory released here

   return 0;
}
Last edited on
What really should be done
1
2
3
4
5
6
7
8
9
#include <iostream>

int main( int argc, char* argv[] )
{
   int myInt= 5;
   std::cout << "myInt is " << myInt << std::endl;

   return 0;
}
Generally agreed.

If you're constantly using the stack then worrying about memory leaks is pointless, though. I thought an example of freeing up allocated heap memory was the best way to go.
Last edited on
Oh, so use destructors and delete stuff
Or you get a memory leak?
Topic archived. No new replies allowed.