• Advertisement
Sign in to follow this  

Dynamic Memory Allocation in C

This topic is 4047 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Can someone point me to a good online tutorial explaining this concept while showing me code samples? I'm not seeming to grasp this concept with the materials I am using.

Share this post


Link to post
Share on other sites
Advertisement
So your village has rocks.

It turns out these rocks are the only thing your village has to write on.

These rocks can't be moved. They are big rocks, after all. But if you let just anyone write on the rocks, there would be chaos.

So there is a system to allocate who gets to use a given rock.

Malloc is this dude who guards the rocks. You go to him, and say "I need about this much rock to write on". He says "sure", gives you a number on a pointy stick (called a Pointer), and says "this is the rock you own".

So now you have a rock. You can look at your Pointer stick (which has the rock number on it) and use it to find your rock. You can then write stuff on your rock and leave notes and messages to yourself.

When you are finished with a rock, you take your Pointer stick back to Malloc's brother, Free. You say "I'm done with the rock this pointer talks about". Free takes your Pointer and tosses it into Malloc's Pool (malloc has a Pool of water where the unused pointers float).

Things get really bad if you accidentally use a Pointer after you return it. You can do this if you make a spare copy of the number on your Pointer (say, on another Rock) and forget that it isn't valid. You could end up writing on a rock that someone else thinks they own -- and your writings will get all messed up! Heck, you could write on the rock yourself, one time thinking you are writing down your grocery list, the other time thinking you are writing your plans for the expansion of your house. Somehow, this ends up with you eating a 2x4 and dieing!

This is why it is important to keep track of your Pointers. :)

In case you didn't figure it out, "rocks" are "memory blocks". Pointers really are numbers that refer to rocks, I mean blocks of memory.

As an aside, when you die (your process ends) Malloc and Free know which pointers you own, and go and get them and return them to the pool. Relying on this, however, isn't polite for a number of reasons (nor is it prudent -- it is a bad habit to get into. Really it is.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement