Dynamic Memory Allocation in C

Started by
2 comments, last by 3dnewbie 17 years, 3 months ago
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.
Advertisement
From [google], the first result I found with malloc tutorial.

http://vergil.chemistry.gatech.edu/resources/programming/c-tutorial/dynamic.html
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.)
Quote:Malloc is this dude who guards the rocks.


rotfl

This topic is closed to new replies.

Advertisement