Runtime error: realloc(): invalid next size

  • 0

    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)
        //if left node present, traverse left
        // add node to array
        int *temp = realloc(res,sizeof(int)*(*returnSize)); 
        res = temp;
        //if right node present, traverse right
     * 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.