1

I have a question regarding memory allocation and deallocation in C++ when reassigning a variable. I've come across a situation where I'm using a stack within a loop and instead of creating a new empty stack for other purpose what will happen if i reassign it to a new empty stack without using the "new" keyword. I'm wondering about the memory management implications of this operation.

stack<int> st;
for (int i = 0; i < n; i++) {
    while (!st.empty() && heights[st.top()] > heights[i]) {
        // Some operations...
        st.pop();
    }
    st.push(i);
}
st = stack<int>(); // Reassigning a new empty stack

Does reassigning a new value (in this case, an empty stack) to the variable st properly release the memory used by the previous stack? Or do I need to explicitly perform memory deallocation to ensure there are no memory leaks?

I'm using GCC version 10.2.1 with the standard C++ library. Any insights and best practices related to memory management in this scenario would be greatly appreciated. Thank you!

  • If you assign a new empty stack, the memory will be released. You might not want that. By contrast, the `clear` method usually does not release memory. – paddy Aug 13 '23 at 11:25
  • When you `pop` the last element of the stack, it might free the memory it has used. If it does is an implementation detail that isn't really relevant. If you leave the loop with the stack still containing elements, you can"`clear" it, like you do or with a loop. That will make the stack empty, and might free memory that was allocated, which still is an irrelevant implementation detail. In short, for any standard container you don' t really have to worry about its internals, as long as the container works as intended. – Some programmer dude Aug 13 '23 at 11:25
  • @paddy I checked for the clear method in stack but it isn't available. – CelestialSapien Aug 13 '23 at 11:26
  • The question is why you would want this in the first place. Instead of `st` your stack should of course have a descriptive name, and if you need a second stack for a different purpose you should create a second stack with a fitting name. If you want use the same stack but need it empty, you should use consider writing a clear method. – infinitezero Aug 13 '23 at 11:27
  • Or, if the stack have a limited life-time, why not let its life end when the scope end, and let the stack destructor do its work? – Some programmer dude Aug 13 '23 at 11:29
  • What if I call st.~stack() before using st=stack(); @Someprogrammerdude – CelestialSapien Aug 13 '23 at 11:34
  • Don't do that. What is your actual goal here? – paddy Aug 13 '23 at 11:38
  • I had to reuse st as an empty stack and was looking for what will be the implications of writing such code. – CelestialSapien Aug 13 '23 at 11:40
  • Instead of reusing it, why not limit its scope and its life-time, and let the compiler and the stack implementation take care of the details? – Some programmer dude Aug 13 '23 at 11:47

0 Answers0