Runtime error: realloc(): invalid next size


  • 0
    S

    Hi, I am trying to implement a recursive solution for the inorder traversal, however, I am getting a run time error saying invalid next size for realloc. I am not sure what the error is. It would be great if someone can point me in the right direction. This is my code

    /**
     * Definition for a binary tree node.
     * 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));
     
        //printf("retSize = %d\t res = %p\t, *res=%d res[0]=%d res[1]=%d \n", *returnSize, res, *res,res[0],res[1]);
        
        //start inorder parsing
        inorder(root, res, returnSize);
        
        return res;
          
    }
    

Log in to reply
 

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