[Solved] leetcode Common Error: :runtime error: member access within misaligned address 0xbebebebebebebebe for type ‘str

Common mistakes of brush force buckle:

runtime error: member access within misaligned address 0xbebebebebebebebe for type ‘struct TreeNode’, which requires 8 byte alignment [TreeNode.c]
0xbebebebebebebebe: note: pointer points here

 


cause:
when we access a variable, it contains an unassigned pointer. Pointers that are defined but not assigned are called wild pointers. The direction of the wild pointer is unknown, which has unknown consequences for the program, and the citation is a big problem. Therefore, C language strictly opposes the wild pointer.

In this topic, use

TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));

The root->left and root->right pointers are not assigned initial values or set to NULL, resulting in an error when assigning values to left and right later.

This can be solved by adding two statements.

TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->left = NULL;	// Here's the problem!!! A null pointer without an assignment must be set to NULL
root->right = NULL;	// 

This is the correct code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

typedef struct TreeNode TreeNode;


TreeNode* CreatTree(int* preorder,int* inorder,int l1,int r1,int l2,int r2){
    if(l1 > r1 || l2 > r2){      // Return NULL
        printf("%d",1);
        return NULL;
    }
    TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
    root->left = NULL;	// Here's the problem!!! A null pointer without an assignment must be set to NULL
    root->right = NULL;	// 
    int i;
    root->val = preorder[l1];
    
    for(i=l2;inorder[i]!=root->val;i++);
    int lLen = i - l2;
    int rLen = r2 - i;
    if(lLen > 0){
        root->left = CreatTree(preorder,inorder,l1+1,l1+lLen,l2,l2+lLen-1);
    }
    
    if(rLen > 0){
        root->right = CreatTree(preorder,inorder,r1-rLen+1,r1,r2-rLen+1,r2);
    }
    return root;

}


struct TreeNode* buildTree(int* preorder, int preorderSize, int* inorder, int inorderSize){
    TreeNode* root = CreatTree(preorder,inorder,0,preorderSize-1,0,inorderSize-1);
    return root;
}

Read More: