Search code examples
c++stack

I was solving a problem on leetcode. I did the code but I am receiving some runtime error saying reference binding to misaligned address


Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.

For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].

Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].

Here is the code that I wrote.

class Solution {
public:
    vector<int> dailyTemperatures(vector<int>& T) {
        stack<pair<int, int>> s;
        vector<int> res(T.size());
        for(int i=T.size()-1; i>=0; i--) {
            if(s.empty()) {
                s.push(make_pair(T[i], i));
                res[i] = 0;
            } else {
                while(s.top().first < T[i]) {
                    s.pop();
                }
                res[i] = s.top().second - i;
                s.push(make_pair(T[i], i));
            }
        }
        return res;
    }
};

and the error that I am getting is given below. Error image


Solution

  • You haven't asked any question, but I'll assume it's

    "Why does this code trigger a runtime error?"

    This code

    while(s.top().first < T[i]) {
        s.pop();
    }
    

    makes no effort to check whether s is empty.

    When s.empty() is true, s.pop() will trigger Undefined Behavior.

    Separately,

    res[i] = s.top().second - i;
    

    also doesn't check if s is empty and triggers Undefined Behavior if it is.