C++ Memory Management Tutorial
This is the second article in the series that I’ll be working on! For those of you who do not already know the basics of C++ and how to compile, etc. I’ll go through a quick run through, but you should visit other sites (Google is a good resource) to find more information! The basics of compilation will be listed below this tutorial! As usual, there will also be a link below to download the whole script as well as compiled binaries!
Here is the main.cpp file:
/**
* Memory Management Tutorial by Dennis M.
* (C) 2009 Dennis M. All Rights Reserved.
*
* This is the basic file to making everything work!
* This isn’t a “basic” tutorial, so it will be less in
* depth than what many may be used to from me.
*
*/#include <iostream>
using namespace std;
// We’re keeping this simple, so we’re going to keep everything
// in just one main()![]()
int main(int argc, char* argv[])
{
/**
* Some memory allocation:
*
* float naturally uses more memory than int and is slower
* but in many cases is more effective from a personal view
* so we’ll use both here.
*
* This is how it works. We’re going to request memory allocation
* BEFORE we actually use it! We’ll allocate 10 bytes to the float var
* and 90 bytes max for the int!
*
*/
float* val1 = new float[10]; // Handle all numbers & initiate it as 0
int* val2 = new int(90); // Start it as 90cout<< “Value 2 + 67 = “<< *val2+67 << endl << endl;
// Try to allocate too much
// the nothrow doesn’t allow this to be allocated if the system
// doesn’t have it..
int* nogo = new (nothrow) int[999999999];
if(!nogo){
cout<< “Your PC doesn’t have enough Memory Available! =-O *shocker*” << endl << endl;
}/**
* Just some other simple work:
* Float Addition!
*
*/
*(val1+1) = 15.123097;
*(val1+8) = 1000.203998124;
cout<< “val1[1] (“<< *(val1+1) <<”) + val1[8] (“<< *(val1+8) <<”) = “<< *(val1+1)+*(val1+8) << endl;// Free all the memory we’ve used
/**
* Delete the arrays: where we used allocation – e.g. delete [] VAR
* Delete the val2 normally
*
*/
delete [] val1;
delete val2;
delete [] nogo;// Set everything to 0!
val1 = 0;
val2 = 0;
nogo = 0;
}
Now that’s all there is to it really. The code is pretty well documented and as always is much of the tutorial! Nothing I really need to explain in it seeing as this is a mainly intermediate tutorial.
As I promised, some compilation techniques:
For most *nix systems (must have gcc installed)
g++ main.cpp -Wall -o mem_management
And for Windows users, I suggest using either Visual C++ by M$ (which the compiler is visual and self-explanatory) or a personally I enjoy Ming (with MSYS) or CyGWIN. With either of those installed, run the command mentioned above for the *nix users and it should all run ok!
As usual, the download link is below:
Memory Management Tutorial Download
Keep an eye for the next few tutorials in the series listed a few posts ago! They should all be great ones!
Regards,
Dennis M.