Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ERROR: AddressSanitizer: negative-size-param: (size=-8)

Sorry for this code, but I have a question.

I tried to solve a LeetCode’s 144 task. Its given that

My solution here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root){
        if(root == nullptr) return{};
        vector<int> visit;
        vector<TreeNode*> stack;
        stack.push_back(root);
        while(stack.size()){
            TreeNode* vt = stack.back();
            stack.erase(stack.end());
            visit.push_back(vt->val);
            if(vt->right!=nullptr)stack.push_back(vt->right);
            if(vt->left!=nullptr)stack.push_back(vt->left);
        }
        return visit;
    }
};

Runtime Error Message

AddressSanitizer: negative-size-param: (size=-8)
=================================================================
==20==ERROR: AddressSanitizer: negative-size-param: (size=-8)
    #5 0x7f3f65eca082  (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
0x602000000060 is located 8 bytes to the right of 8-byte region [0x602000000050,0x602000000058)
allocated by thread T0 here:
    #4 0x7f3f65eca082  (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
==20==ABORTING

but when I use stack

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root){
        if(root == nullptr) return{};
        vector<int> visit;
        stack<TreeNode*> stack;
        stack.push(root);
        while(stack.size()){
            TreeNode* vt = stack.top();
            stack.pop();
            visit.push_back(vt->val);
            if(vt->right!=nullptr)stack.push(vt->right);
            if(vt->left!=nullptr)stack.push(vt->left);
        }
        return visit;
    }
};

I want use vector as a stack, but where is my mistake?

>Solution :

The statement

stack.erase(stack.end());

is wrong.

From this erase reference:

The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos.

You already have the simple and plain solution: Use an actual stack as the stack.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading