Dynamic Memory

Started by
7 comments, last by hereticprophecy 17 years, 2 months ago
Dynamic Memory: does increasing the size of a dynamic array delete stored values? Below is the whole story, if you care to help me out. If not, any sort of answer would be helpful. I'm in the process of learning C++ after learning C in full, and I've run into a snag. My current project is a simple baseball scorer, where the user inputs hits (single, double, triple, or homer) and the program translates successive hits into runs and totals each each team's score. Getting that to work was hardly a problem, and so I've tried to embellish the working program a bit by adding a few user-friendly additions, namely a 'recovery' function that, in theory at least, logs all user inputs and allows for corrections. With my limited knowledge, dynamic memory seems to be the perfect fit for such a logging system: set the array's size to a variable, and as needed increase the array's size to fit all the data put into the program. Toss in a few pointers to help with the correction process and voila! a correction process for any possible length of game. Before even adding the function to the program itself, I began fooling around with dynamic memory to see exactly how it works...and I'm stumped. The array is assigning seemingly random values that change each time the size of the array is increased. I've tried initiallizing each node manually, but the same problems keep coming up.
Advertisement
If the content of the array is changed when resizing the array, then there's something happening during the process where you allocate a new, larger, block of memory and copy the data from the old to the new block. Since you knew C fully, this shouldn't be much of a problem, since the idea is exactly the same in C++. Post some code.

But since you're using C++, may I suggest the standard library? std::vector is a self-adjusting dynamicly sized container.
Here's a portion of the 'void Log_()' function I'm using to handle all of the inputs into the dynamic memory array.

int * Log_Helper_ = new (nothrow) int [Log_Size_];         //Global initializationvoid Log_(){   switch (Command_)      {         case 1:	 {            Log_Size_ ++;	    *Log_Helper_ = 1; Log_Helper_ ++;	    for (i = 0; i < Log_Size_; i ++)                //For Debug purposes		    {						       cout << Log_Helper_ << " ";			    }	    if (Log_Helper_ == 0)	    {	       cout << "Error logging last entry. Attempting to relog...\n";	       Log_Size_ ++;	       *Log_Helper_ = 1; Log_Helper_ ++;	       if (Log_Helper_ == 0)	          cout << "Attempt failed. Last entry will not be logged.\n";	       else cout << "Attempt successful. Last entry logged.\n";	    }            break;      }


...and so on. If the user input a single being hit, a translator funtion will take that string and change it into numerical values (for ease in logging). The translator then passes that number to this function and this section of the switch will run.

I placed the debug loop to let me monitor the changes being made to the log array, and when it prints the logged values, they are nothing close to what I thought were put in. In all honesty, I think I've mislabeled the pointers, and that is gonna be my mission today.
Let's assume that Log_Size_ is four:
int * Log_Helper_ = new (nothrow) int [Log_Size_];         //Global initializationA chunk of memory:     chunk of allocated memory     +-------------------+     v                   v+----+----+----+----+----+----+----+----+|    |    |    |    |    |    |    |    |+----+----+----+----+----+----+----+----+       ^       |       Log_Helper_void Log_(){   switch (Command_)      {         case 1:	 {            Log_Size_ ++;	    *Log_Helper_ = 1; Log_Helper_ ++;A chunk of memory:     chunk of allocated memory     +-------------------+     v                   v+----+----+----+----+----+----+----+----+|    |   1|    |    |    |    |    |    |+----+----+----+----+----+----+----+----+            ^            |            Log_Helper_	    for (i = 0; i < Log_Size_; i ++)	//For Debug purposes		    {						       cout << Log_Helper_ << " ";		A chunk of memory:     chunk of allocated memory     +-------------------+     v                   v+----+----+----+----+----+----+----+----+|    |   1|    |    |    |    |    |    |+----+----+----+----+----+----+----+----+            ^    ^    ^    ^    ^            |    |    |    |    |            |    |    |    |    Log_Helper_[4]            |    |    |    Log_Helper_[3]            |    |    Log_Helper_[2]            |    Log_Helper_[1]            Log_Helper_[0]	    }

Note that incrementing Log_Size_ does absolutely nothing to change the amount of memory you've allocated and that in your loop you print data which is outside your chunk of allocated memory. This is undefined behaviour. What you need to do is, if your chunk of allocated memory is too small, allocate a larger chunk and copy the existing data across. The aforementioned std::vector will do this for you.

Σnigma
That's exactly what I needed to know. Thank you!
I've gotten it to work with std::vector, and now I'm left wondering...

What is the point of dynamic memory when a std::vector can do the same with greater flexibility?
Quote:Original post by hereticprophecy
I've gotten it to work with std::vector, and now I'm left wondering...

What is the point of dynamic memory when a std::vector can do the same with greater flexibility?


Because thats what std::vector uses "under the hood". I can't remember the last time I've used new[] or delete[], even regular delete is a rare occurance when you get used to smart pointers like std::auto_ptr and boost::shared_ptr.
Indeed, with the standard library containers and references there is very little reason to use pointers directly in your code. However, there are still uses. The big one is polymorphism and there are others, but I can't think of them off-hand.

C++: A Dialog | C++0x Features: Part1 (lambdas, auto, static_assert) , Part 2 (rvalue references) , Part 3 (decltype) | Write Games | Fix Your Timestep!

I actually got in an argument with a friend of mine while in our C programming class. During our lab, I made a comment on how I figured I could do the lab easier without pointers, and he (having known C++ for quite a while) scolded me for thinking them completely useless. I guess he was right, heh.

This topic is closed to new replies.

Advertisement