【发布时间】:2017-10-21 01:53:46
【问题描述】:
我正在尝试实现一个中序遍历,它返回一个包含遍历值的数组。在我的递归方法中,我尝试使用realloc() 函数来修改数组的大小并存储结果。但是,我收到以下错误:
realloc(): invalid next size。
以下是我的代码:
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
void inorder(struct TreeNode *root, int *res, int *returnSize)
{
if(root == NULL)
return;
//if left node present, traverse left
inorder(root->left,res,returnSize);
// add node to array
res[(*returnSize)]=root->val;
(*returnSize)++;
int *temp = realloc(res,sizeof(int)*(*returnSize));
res = temp;
//if right node present, traverse right
inorder(root->right,res,returnSize);
}
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
//check if root == null
if(root == NULL)
{
return root;
}
//malloc result array to return
int *res = (int *)malloc(sizeof(int)*(*returnSize));
//start inorder parsing
inorder(root, res, returnSize);
return res;
}
【问题讨论】:
-
一方面你没有检查
realloc()的返回值。在调用这个之前,*returnSize是什么? -
见:Do I cast the result of malloc?。同样
int *temp = realloc (res, sizeof *temp * return Size); if (!temp) return res; res = temp;将验证realloc的返回,并防止在realloc失败时丢失指向res的指针。 -
请注意,
inorderTraversal中的res不会在inorder中更新,因为按值调用。
标签: c runtime-error binary-tree inorder