Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a memory leak in C++?

I was just wondering how you could create a system memory leak using C++. I have done some googling on this but not much came up, I am aware that it is not really feasible to do it in C# as it is managed code but wondered if there was a simple way to do this with C++? I just thought it would be interesting to see how much the system suffers because of code not being written properly. Thanks.

like image 820
Bali C Avatar asked Aug 30 '11 11:08

Bali C


People also ask

How do memory leaks occur in C?

Types of Memory Leaks Occurs when you free a block of memory that contains pointers to other memory blocks. Occurs when a function returns a pointer to an allocated block of memory, but the returned value is ignored in the calling routine.

How do you create a memory leak?

Just forgetting to set a reference to null or more often forgetting to remove one object from a collection is enough to make a memory leak. Of course all sort of listeners (like UI listeners), caches, or any long-lived shared state tend to produce memory leak if not properly handled.

Does C have memory leak?

C # in TeluguThe memory leak occurs, when a piece of memory which was previously allocated by the programmer. Then it is not deallocated properly by programmer. That memory is no longer in use by the program. So that place is reserved for no reason.

How do I create a memory leak in CPP?

Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator.


3 Answers

A memory leak occurs when you call new without calling a corresponding delete later. As illustrated in this sample code:

int main() {     // OK     int * p = new int;     delete p;       // Memory leak     int * q = new int;     // no delete } 
like image 185
StackedCrooked Avatar answered Sep 21 '22 17:09

StackedCrooked


  1. Create pointer to object and allocate it on the heap
  2. Don't delete it.
  3. Repeat previous steps
  4. ????
  5. PROFIT
like image 27
Tony The Lion Avatar answered Sep 22 '22 17:09

Tony The Lion


int main() {
    while(true) new int;
}
like image 26
Puppy Avatar answered Sep 25 '22 17:09

Puppy