Search code examples
c++runtime-errorc++14binary-tree

runtime error while merging 2 binary trees


I'm trying to solve merging binary trees problem from leetcode. Here is my c++ code

    class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        TreeNode *t;
        if(t1==nullptr){return t2;}
        if(t2==nullptr){return t1;}
        t->val=t1->val+t2->val;
        t->left=mergeTrees(t1->left,t2->left);
        t->right=mergeTrees(t1->right,t2->right);
        return t;
    }
};

This code is producing the following error

Line 18: Char 12: runtime error: member access within misaligned address 0x000000000001 for type 'TreeNode', which requires 8 byte alignment (solution.cpp)
0x000000000001: note: pointer points here
<memory cannot be printed>
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:27:12

However if I tried to solve without using an extra TreeNode as shown below it's working fine

class Solution {
public:
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        //TreeNode *t;
        if(t1==nullptr){return t2;}
        if(t2==nullptr){return t1;}
        t1->val=t1->val+t2->val;
        t1->left=mergeTrees(t1->left,t2->left);
        t1->right=mergeTrees(t1->right,t2->right);
        return t1;
    }
};

Can someone please explain why the first code is causing the error ?


Solution

  • In this code

    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        TreeNode *t;
        if(t1==nullptr){return t2;}
        if(t2==nullptr){return t1;}
        t->val=t1->val+t2->val;
    

    t is an uninitialised pointer, and therefore t->val is an error.

    Presumably you meant something like this

    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        if(t1==nullptr){return t2;}
        if(t2==nullptr){return t1;}
        TreeNode *t = new TreeNode;
        t->val=t1->val+t2->val;