Bad memory access in my code


  • 0
    O
    int getListLength(ListNode *head)
    {
        ListNode *p = head;
        int length = 0;
        
        while(p != NULL) {
            p = p ->next;
            length++;
        }
        
        return length;
    }
    
    TreeNode *sortedListToBST(ListNode **head, int start, int right)
    {
        if(start > right) {
            return NULL;
        }
        
        int mid = (start + right) / 2;
        TreeNode *leftTree = sortedListToBST(head, start, mid - 1);
        TreeNode *root;
        root ->val = (*head) ->val;
        *head = (*head) ->next;
        TreeNode *rightTree = sortedListToBST(head, mid + 1, right);
        
        root ->left = leftTree;
        root ->right = rightTree;
        
        return root;
    }
    
    TreeNode *sortedListToBST(ListNode *head)
    {
        int length = getListLength(head);
        
        if(length <= 0) return NULL;
        
        return sortedListToBST(&head, 0, length - 1);
    }
    

    My Code has a bug for bad memory access.
    In the function sortedListToBST(ListNode **head, int start, int right), line 7, who assign the node's value to the root node, (*head) ->val.

    In my XCode, I could see everything in the memory block when in debug mode, however the code just could not access the memory and assign value after 1 or 2 recursion.

    Can someone help me to fix this problem? Thank you!


  • 0
    S

    You can't just define a pointer to TreeNode ('TreeNode* root'), leave it uninitialized, and try to assign any value to its (non-existent) member. You must actually allocate space for this object:

    TreeNode* root = new TreeNode((*head)->val);

  • 0
    O

    OK. Thank you for your help!


Log in to reply
 

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