Page 1 of 1

Defeating Mr. Memory Leak Dynamically allocated memory pitfalls Rate Topic: -----

#1 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3089
  • View blog
  • Posts: 19,137
  • Joined: 14-September 07

Posted 01 December 2008 - 02:41 PM

*
POPULAR

Defeating Mr. Memory Leak


“Typical”, I thought as I headed down to the interrogation room. I enter the dark decrepit crawlspace that the city has allocated for inquisition of criminals.

“Who do we have today?” I ask the guard on duty.

“We picked up this memory leak down the street,” came the reply, “He was acting suspicious, so we hauled him in for questioning.”

“I see. Give me the case file.”

I proceeded to enter the room. The single bulb fixture added to the already depressing mood as I sat down.

“Hello, I am Mr. Atchison, may I ask who you are?”

“My name is Leak, Memory Leak.”

“I see. Mr. Leak, do you know why you are here?”

“In fact I do. I was seen leaving the scene of a robbery.”

“So you confess then?”

“No, it wasn’t my fault, it was the other group members.”

“I believe you need to explain yourself Mr. Leak”

“Very well, it all began a few days ago…” He opens the case file:


class Car
{
      public:
             Car() {};
             ~Car() {};
             void getAway() {};
};
      

int main()
{
    //We decided to steal some cars from the local dealership
    //in the beginning our plan was going so well
    Car* stolenCar = new Car();
    
    //We allocated the memory and everything
    stolenCar->getAway();
    
    //We got away and we thought that was it
    //As you can see we leaked memory
}




“I could have sworn we made a clean get away.” He exclaims.

“Apparently not.” I reply. “Do you see where the memory leak was created?”

“Now I do,” he says. “If I only I called delete on our stolen Car, we could have avoided all of this mess.”

“You are absolutely right, but this isn’t the only incident is it?” I ask.

“No” He sighs and turns to the next page in the case file:


int main()
{
    //After our supposed get away from the previous robbery, we decided to steal an array of cars
    Car* carStorage = new Car[5];
    
    //We allocated the memory and everything
    
    //Learning from our past mistakes we even called delete to 
    //make sure the police could not follow us
    //But i'm sure you knew we leaked memory again
    
    delete carStorage;
    return 0;
}



“Indeed. Do you know why?” I inquire.

“Not really” He replies.

“Well, when you allocate a pointer to an array of data you must use the [] operator to clean up after your pointer. Otherwise you only delete the first element and the rest of it is leaked.”

“That makes so much sense now” His face seems stuck in amazement. “I knew we leaked memory somehow.”

“I see the offense you got dragged in here on is next in the file.”

“It is.” He turns the page:


int main()
{
    //What better way to hold all of our stolen goods, then in a vector?
    //If only we had known...
    vector<Car*> ourCars;
    
    Car* temp; //our temporary storage device
    
    //We allocated the memory and everything
    for(int i = 0; i < 5; i++)
    {
          temp = new Car();
          ourCars.push_back(temp);  
    }
    
    //Learning from our past mistakes we even called delete to 
    //We hid out for a few days
    //We need had to clean up after our vector
    for(int i = 0; i < 5; i++)
    {
          ourCars.erase(i);//we thought this would take care of it
    }
    
    return 0;
}



“That is awful. You leaked all the memory in that vector.”

“I see that now, but I’m not entirely sure how we did that, I mean, we erased all the pointers.”

“You effectively erased all the handles to the allocated memory. It is now cut off from the system. Too much of that and the whole unit could crash.”

“I’m so sorry!” he sobbed.

“It’s worthless now! The damage is already done.”

“What is going to happen to me?”

“What people fail to realize is that memory leaks don’t spontaneously occur. They are the result from poorly designed code.”

“Wha…?”

“Therefore I will show you how to correctly allocate and free memory and you will be set free.”

“Oh thank you. Thank you.”

“Now look here” I open a folder on the desk:


Case 1:

class Car
{
      public:
             Car() {};
             ~Car() {};
             void getAway() {};
};
      

int main()
{
    //We decided to steal some cars from the local dealership
    //in the beginning our plan was going so well
    Car* stolenCar = new Car();
    
    //We allocated the memory and everything
    stolenCar->getAway();
    

//********* FREE your car***************
 delete stolenCar;
 return 0;
}



Case 2:

int main()
{
    //After our supposed get away from the previous robbery, we decided to steal an array of cars
    Car* carStorage = new Car[5];
    
    //We allocated the memory and everything
    
    //Learning from our past mistakes we even called delete to 
    //make sure the police could not follow us
    //But i'm sure you knew we leaked memory again
    
//If you allocate an array of memory, delete an array of memory, use []
    delete [] carStorage;
    return 0;
}



Case 3:

int main()
{
    //What better way to hold all of our stolen goods, then in a vector?
    //If only we had known...
    vector<Car*> ourCars;
    vector<Car*>::iterator iter;//use an iterator
    
    Car* temp; //our temporary storage device
    
    //We allocated the memory and everything
    for(int i = 0; i < 5; i++)
    {
          temp = new Car();
          ourCars.push_back(temp);  
    }
    
    //Free the allocated memory
    for(iter = ourCars.begin(); iter != ourCars.end(); iter++)
    {
             delete (*iter);
    }
    ourCars.clear(); //gets rid of all the handles
    
    return 0;
}



“Now that you know, I’m going to release you. But be careful when dealing with dynamic memory allocation/pointers. It is both C++’s greatest strength and greatest downfall for inexperienced programmers.”

“I will. I will. Thank you!” He gleefully leaves.

“I’m sure he’ll be back…”


Is This A Good Question/Topic? 23
  • +

Replies To: Defeating Mr. Memory Leak

#2 crazyjugglerdrummer  Icon User is offline

  • GAME OVER. NERD WINS.
  • member icon

Reputation: 119
  • View blog
  • Posts: 690
  • Joined: 07-January 09

Posted 31 March 2009 - 02:03 PM

The funniest tutorial format I've ever seen! and helpful too :)
Was This Post Helpful? 0
  • +
  • -

#3 athlon32  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 116
  • View blog
  • Posts: 363
  • Joined: 20-August 08

Posted 06 November 2009 - 06:04 PM

KYA said:

“I’m sure he’ll be back…”


LMFAO :lol:

Case 3, was very helpful. thanks :^:
Was This Post Helpful? 0
  • +
  • -

#4 Fib  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 161
  • View blog
  • Posts: 554
  • Joined: 12-March 09

Posted 13 May 2010 - 11:52 AM

What an amazing way to present a tutorial! Good job KYA! :^: :^:
Was This Post Helpful? 0
  • +
  • -

#5 stefaan  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 22-November 08

Posted 13 May 2010 - 11:55 PM

Good job man! this is really helpful, esp case 3
Was This Post Helpful? 0
  • +
  • -

#6 remorseless  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 29
  • View blog
  • Posts: 129
  • Joined: 08-August 09

Posted 02 July 2010 - 03:50 AM

Wow! Amazing tutorial :D Very good
Was This Post Helpful? 0
  • +
  • -

#7 RetardedGenius  Icon User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 125
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Posted 28 July 2011 - 02:37 AM

A unique way of presenting it but it made me laugh and got the important parts through my thick skull! I've written over a hundred small C++ programs now, without once even thinking about memory management, I've probably leaked memory all over the place!

I thought that when a program has finished executing and is closed, the memory is deallocated accordingly? Also aren't local variables in blocks and functions automatically deallocated when they are exited as well?
Was This Post Helpful? 0
  • +
  • -

#8 RudiVisser  Icon User is offline

  • .. does not guess solutions
  • member icon

Reputation: 1001
  • View blog
  • Posts: 3,555
  • Joined: 05-June 09

Posted 28 July 2011 - 07:29 AM

View PostRetardedGenius, on 28 July 2011 - 10:37 AM, said:

I thought that when a program has finished executing and is closed, the memory is deallocated accordingly? Also aren't local variables in blocks and functions automatically deallocated when they are exited as well?

Unfortunately, C(++) has no GC unlike most "modern" languages such as C#, Objective-C, and dare I say even PHP?! But that's not real anyway :D

You can however implement an automatic GC into C, there's a few projects out there.

This post has been edited by RudiVisser: 28 July 2011 - 07:30 AM

Was This Post Helpful? 1
  • +
  • -

#9 PlasticineGuy  Icon User is offline

  • mov dword[esp+eax],0
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,436
  • Joined: 03-January 10

Posted 30 July 2011 - 09:01 PM

Most operating systems do deallocate heap memory once a process terminates.
Was This Post Helpful? 0
  • +
  • -

#10 AKMafia001  Icon User is offline

  • </code.in.dream>

Reputation: 183
  • View blog
  • Posts: 616
  • Joined: 11-June 11

Posted 17 September 2011 - 12:10 AM

For a while i thought why you let him go away. Then i came to know that,

Quote

“I’m sure he’ll be back…”

you want to expose all his leaks. :P
Was This Post Helpful? 0
  • +
  • -

#11 Ricky65  Icon User is offline

  • D.I.C Head

Reputation: 38
  • View blog
  • Posts: 115
  • Joined: 03-June 10

Posted 23 September 2011 - 03:58 PM

I admire the OP's wit but this isn't leak proof...

People are much better off using std::unique_ptr and std::shared_ptr and avoid using operator delete at all. Prefer std::unique_ptr and unique ownership of pointers as std::shared_ptr is not cheap. Trust me, it will save you a lot of hassle.

This post has been edited by Ricky65: 23 September 2011 - 03:59 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1