I did a leetcode question and for following solution ASAN is kicking:
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
if (root == nullptr) return vector<int>();
int ans[205];
memset(ans, -1, sizeof ans);
queue<pair<TreeNode*,int>> q;
int ml = 0;
q.push({root, 0});
while(!q.empty()) {
const auto &[node, level] = q.front();
q.pop();
ml = max(ml, level);
if (ans[level] == -1) ans[level]=node->val;
if (node->right != nullptr) q.push({node->right, level+1});
if (node->left != nullptr) q.push({node->left, level+1});
}
return vector<int>(ans,ans+ml+1);
}
};
If I replace const auto &[node,level]=q.front();q.pop();
with normal auto pair=q.front();node=pair.first,level=pair.second;
, it works fine. Can anyone help me understand what's going on in above solution?
const auto &[node, level] = q.front();
q.pop();
You get a reference to the front node and then immediately destroy the node resulting in a dangling reference. Move q.pop();
to the loop body end.