954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

The definiton of "Memory leaks"

Could anyone define "Memory leaks" well ?
'cause pretty hard for me to understand with C++ books.

tenoran
Newbie Poster
9 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

A memory leak is simply allocating memory and failing to release it when you're done. Technically, the following illustrates a memory leak:

#include <iostream>

using namespace std;

int main()
{
  int *p = new int;

  *p = 10;

  cout<< *p << endl;
}

In practice, the operating system will typically reclaim all memory allocated to a process when the process terminates, but that's not required by the language definition. However, long running programs can consume all fast memory and grind the program to a near halt, or crash the system if virtual memory is also exhausted. So any call to new must be paired with a call to delete:

#include <iostream>

using namespace std;

int main()
{
  int *p = new int;

  *p = 10;

  cout<< *p << endl;

  delete p;
}
Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Thank you for the answer.

tenoran
Newbie Poster
9 posts since Mar 2005
Reputation Points: 10
Solved Threads: 0
 

the best bit is creating a loop of new arrays and watching the memory size increase :D

Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

Hello Acidburn,

If you are going to do that, be sure to save your work first! I have done some expirements with linux processes, and was able to crash a computer in 20 seconds or so.

Christian

kc0arf
Posting Virtuoso
Team Colleague
1,937 posts since Mar 2004
Reputation Points: 121
Solved Threads: 57
 

20 secs? may I have a look at the code? I'm running windows and it just fills up the memory very slowly ...took around 4 hrs! .. .:S

Acidburn
Posting Pro
511 posts since Dec 2004
Reputation Points: 12
Solved Threads: 5
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You