C++ strange error, anyone can help? thanks


  • 0
    H

    Line 17: member access within misaligned address 0x000100000006 for type 'struct mynode', which requires 8 byte alignment

    Anyone knows what happened? Thanks.

    struct mynode{
        struct mynode *left;
        struct mynode *right;
        int val;
        int sum;
        mynode(int num,int def=1){
            val=num;
            sum=def;
        }
        
    };
    class Solution {
    public:
        mynode* helper(mynode* root,int num,int& pre){
            if(root==NULL)
                root=new mynode(num);
            else if((root->val) > num)      //line17  error
                root->left=helper(root->left,num,pre);
            else if((root->val) < num){
                pre+=root->sum;
                root->right=helper(root->right,num,pre);
            }
            else
                root->sum++;
            return root;
        }
        vector<int> countSmaller(vector<int>& nums) {
            vector<int> v;
            int pre,size=nums.size();
            if(size==0) return v;
            mynode *root=new mynode(nums[size-1],0);
            for(int i=size-1;i>=0;i--){
                pre=0;
                helper(root,nums[i],pre);
                v.push_back(pre);
            }
            reverse(v.begin(),v.end());
            return v;
        }
    };
    

  • 0

    You're leaving left and right of newly created mynode objects undefined. Initialize them as null pointers.


  • 0
    H

    yes, that is the problem.
    thank you.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.