title: Problems when freeing memory when I have undo/redo
body: <p>I'm working on a project for a class where we are supposed to implement basic functionality for a text editor, including undo and redo. I currently have my undo/redo functions working correctly, the only problem is, is that I'm getting a valgrind error when trying to free the memory from a <code>Command</code> object that tells us what to execute.</p>
  
  <p>This <code>Command</code> object is part of a struct within a namespace like so:</p>
  
  <pre><code>struct UserInteraction
  {
      UserInteractionType type;
      Command* command;
  };
  </code></pre>
  
  <p>Currently, I store each command that the user issues in a std::vector of type <code>&lt;UserInteraction&gt;</code> called <code>undoStack</code>. I also have a <code>redoStack</code> of the same type which is also a std::vector. Storing each command looks like this:</p>
  
  <pre><code>    else if (interaction.type == UserInteractionType::command) // COMMAND
      {
          try
          {
              interaction.command-&gt;execute(editor);
              commandInteraction = true;
              undoStack.push_back(interaction);
              view.clearErrorMessage();
          }
          catch (EditorException&amp; e)
          {
              delete interaction.command;
              view.showErrorMessage(e.getReason());
          }
          view.refresh();
      } // end if-else
  </code></pre>
  
  <p>I need to deallocate each UserInteraction that was pushed into the vector, when the user presses ctrl+x (which exits the program). Otherwise, any command I issue gives me a error like this:</p>
  
  <p><code>4 bytes in 1 blocks are definitely lost in loss record 2 of 38</code></p>
  
  <p>Where each command entered increases the amount of bytes by lost by 4.</p>
  
  <p>I figured I just needed to deallocate all the memory used by each vector within the quit command, but all the current solutions that people use seem to still give me memory leaks. Here are two versions of my quit method (both of which still give me memory leaks):</p>
  
  <p>First try:</p>
  
  <pre><code>    if (interaction.type == UserInteractionType::quit)
      {
          clear undo
          std::vector&lt;UserInteraction&gt;().swap(undoStack);
          clear redo
          std::vector&lt;UserInteraction&gt;().swap(redoStack);
          break;
      }
  </code></pre>
  
  <p>And my second try at deallocating memory:</p>
  
  <pre><code>    if (interaction.type == UserInteractionType::quit)
      {
          undoStack.clear();
          undoStack.shrink_to_fit();
          redoStack.clear();
          redoStack.shrink_to_fit();
          break;
      }
  </code></pre>
  
  <p>So how can I actually deallocate everything in both vectors?</p>