刷力扣时常犯的错:
runtime error: member access within misaligned address 0xbebebebebebebebe for type ‘struct TreeNode’, which requires 8 byte alignment [TreeNode.c]
0xbebebebebebebebe: note: pointer points here
原因:
我们在访问某个变量时,因为这个变量中含有未赋值的指针。定义但是不赋值的指针叫做野指针。野指针指向不明,对程序有不可知的后果,引用了更是出大问题,所以,c语言严格反对野指针。
在这个题目中,使用
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
申请了一块内存空间给root结点,然而并没有对root->left和root->right指针赋初值也没有置为NULL。导致后面给left和right赋值时报错。
若加上两条语句,则可解决:
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));root->left = NULL;// 问题在这里!!没有赋值的空指针一定要设为NULLroot->right = NULL;//
这是一段正确的代码:
/** * 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){// 说明此时无孩子,返回NULLprintf("%d",1);return NULL;}TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));root->left = NULL;// 问题在这里!!没有赋值的空指针一定要设为NULLroot->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;}