Stack challenge - improving memory consumption
My main problem is that you are dynamically allocating all objects with new and or malloc. In C++ object can be created locally without new just by declaring them in the local scope.

MyStack   stack;      // Creates and initializes a MyStack object.


MyStack   data[10];   // Create and initialize an array of MyStack objects.


See no need to call new at all most of the time.

The second problem is that you are using malloc. This is C memory management. The blocks are not necessarily in the same areas as memory allocated by new and thus not compatible to be deleted by either. Also they don't run the constructor and free will not run the destructor. So a very bad idea.

The third observation is that you are building a container (linked list). There is already a built-in linked list.

std::list&lt;int&gt;   data;


For this structure of a stack. The list is not the optimal data structure. A std::vector or std::deque is probably better. But we have a built-in std::stack which is actually a container adapter that wraps another container type (by default it uses std::deque).

std::stack&lt;int&gt;   data;  // This is probably your best option
                         // for holding data.


If you want multiple stacks. I would just create a std::vector of stacks that you can the size at runtime to get all the stacks you need.

std::vector&lt;std::stack&lt;int&gt;&gt; data;
data.resize(&lt;Number-Of-Stacks-You-Need&gt;);


That should solve your memory problems.

Looking at your code we could go into your design of MyStack (but I think that is superflous). But some common rules:


Don't use C facilities when better C++ ones exist.
scanf() => operator&gt;&gt;
Don't mix dynamic memory allocation.
Only use new and delete in C++ code.
Every call to new should be matched with a call to delete
But you should not even do that normally:
a. Use local object most of the time.
b. Use containers when you have groups of objects.
c. When you really need dynamic allocation use smart pointers.
Learn the Rule of 3