# Why this code has a bag that is "double free or corruption"

• The following version of code is error. But if I can use new TreeNode(nums[mid]) instead of using middleNode(nums, left, right); , this error was solved. I don't know the difference between new and malloc. Please give me the reason why.

``````class Solution {
public:
TreeNode* middleNode(vector<int>& nums, int left, int right){
TreeNode* mid = (TreeNode*)malloc(sizeof(TreeNode));
mid->val = nums[(left + right)/2];
return mid;

}

TreeNode* recursive(vector<int>& nums, int left, int right){
if(left > right) return NULL;
int mid = (left + right)/2;
// TreeNode* node = new TreeNode(nums[mid]);
TreeNode* node = middleNode(nums, left, right);
if(left == right) return node;
node->left = recursive(nums, left, mid -1);
node->right = recursive(nums, mid + 1, right);
return node;
}

TreeNode* sortedArrayToBST(vector<int>& nums) {
if(nums.size() == 0) return NULL;
TreeNode* root = recursive(nums, 0, nums.size()-1);
return root;
}
};

``````

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