0

Trying to learn datastructures, I made this class for a stack. It works just fine with integers but it throws a mysterious error with strings. The class List is the API for my stack. Its meant to resize automatically when it reaches the limit. The whole code is just for the sake of learning but the error I get doesn't make any sense and it happens somewhere in some assembly code.

#include <iostream>
#include<string>
using namespace std;


class List {
private:
    
    int N = 0;
    string* list = new string[1];
    void resize(int sz) {
        max = sz;
        string* oldlist = list;
        string* list = new string[max];
        for (int i = 0; i < N; i++) {
            list[i] = oldlist[i];
        }

    }
    int max = 1;
public:
    void push(string str) {
        if (N == max) {
            resize(2 * N);
        }
        cout << max << endl;
        list[N] = str;
        N++;
    }
    void pop() {
        cout << list[--N] << endl;
    }


};
int main()
{

    string in;
    List list;
    while (true) {
        cin >> in;
        if (in == "-") {
            list.pop();
        }
        else {
            list.push(in);
        }
    }
}
5
  • What is the "mysterious error"? Commented Feb 9, 2022 at 21:34
  • When you see an error in assembly code, that's probably some optimized library somewhere. Use the debugger's backtrace to dig back to your code and see what you were doing that finally blew up a few function calls down the stack. Commented Feb 9, 2022 at 21:38
  • 1
    Side note: beside code it is nice to provide example input. Commented Feb 9, 2022 at 21:43
  • 1
    Even better to build the input into the code example so it can easily be run over and over with the same set. Commented Feb 9, 2022 at 21:45
  • godbolt.org/z/r1M74dbGe Commented Feb 9, 2022 at 21:45

1 Answer 1

2

string* list = new string[max]; in the resize method defines a new variable named list that "shadows", replaces, the member variable list. The member list goes unchanged and the local variable list goes out of scope at the end of the function, losing all of the work.

To fix: Change

string* list = new string[max];

to

list = new string[max];

so that the function will use the member variable.

Don't forget to delete[] oldlist; when you're done with it to free up the storage it points at.

Sign up to request clarification or add additional context in comments.

2 Comments

Recommendation: read up on the Rule of Three
I see, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.