Skip to end of metadata
Go to start of metadata


C++ is my extension language, so all of these are extensions. 


1) The goal of this task was to explore how memory management happens in C++.  Since C++ can allocate and deallocate memory the same as in C, I took the opportunity to see if there are other options for how to deal with memory in C++.  I found that in addition to the malloc and free options for allocating and deallocating memory, there is also a new and delete option.  

Here are some examples:

This is uses malloc and free just like in C: an array of num integers is malloced, fill with 0-num, printed, and then freed. Here is the output from this process:

The second option is to use new and free like in this example:

This does the same as the first: it allocates memory for an array with num ints in it, and then fills it with 0-num, prints the list and then deletes it:

2) On the surface it seems like these two things are interchangeable: that new and delete just make it a little bit easier for the programmer.  I decided to compare how long it takes the malloc or new  the same size memory block multiple times to see if there is a time advantage for one over the other:

I did four example like this:

 This makes 10,000 of chars using malloc and malloc and times how long it takes.  It then does the same thing with delete and new.  I then do the same thing with 10,000 long doubles, and an array with 1,000,000 integers.  Here were the results:

In all of the cases the malloc and free takes slightly (although very slightly) longer than new - except the first one, but in all of the other test that I did, the first always takes significantly longer than the rest.  I tried to fix this problem by mallocing and freeing one first, but it did not work.  So, it is hard to tell if this difference is due to the malloc and free operations or from the fact that that was the first allocating.  

3) I made a haiku to show the new way to allocate and deallocate memory in C.

This shows how int arrays can be allocated using new and then deallocated using delete. 


  • No labels