We are going back to Nick Parlante's Pointers & Memory tutorial.
Section #4 - Heap Memory
While we provide a PDF version of the above-mentioned tutorial, you might want to follow this link to
Nick Parlante's web site and download the latest version and peruse the excellent material available there.
We are going to start off with a mix of lecture and live programming to take a first look at how memory might
be dynamically allocated at runtime. We will also experiment with a first bug which we might fall for if we don't
understand thoroughly functions.
If you have been programming in C++, you are already used to allocating memory at runtime for objects when you need them.
Instead of new and delete, which are adapted to the object-oriented nature of C++, we will be using a lower-level
API here which only allows you to request specific amounts of memory, which size is expressed in bytes, which you may then
manipulate as you see fit.
For those of you who have been studying Java, you are in for a surprise. Java allows you to request memory at runtime
but takes cares of discarding it by itself when it's no longer being used. The process is referred to as "Garbage Collection".
No such thing here, if you allocate some memory at runtime, you need to keep track of when you don't need it anymore and de-allocate
it by hand.
We are going to revisit our "Handy Arrays Library" and use our newly acquired knowledge on dynamical memory
allocation to extend it. This will give us a bit of experience in allocating dynamically arrays of int.
However, when you know how to do it with dynamical arrays of int, you will see that you are ready to do it with
arrays of just about any elementary and even non-elementary data types.
Same for our "Handy String Library", the added advantage is that you should start seeing the link between arrays, pointers and strings.
Many similarities which often obfuscate the subtle yet fundamental & bug-generating differences.
Another exercise illustrating how dynamical memory allocation and pointers relate to arrays.
This time we go for the dreaded second dimension. We not only build a set of functions meant to handle
2D matrices which are allocated by hand but, by doing so, also give you hints about how multi-dimensional arrays
are stored in memory.
This will go a long way to help you understand the equivalences between formal and effective array parameters.
E.g. When you pass an effective parameter of data type "array of int" it is understood as the same as "const int *".
Thing only get more elaborate as we manipulate multi-dimensional arrays...
For this series of videos, we won't be exploring the issue further but you need to be aware of the monsters lurking
in the shadows, I mean gray areas.