Search code examples
c++structurereturn-type

C++ return type pointer to a structure leetcode


I need help with a return value for one of the leetcode questions I am attempting. I am instantiate a structure and then return the pointer to the structure.

 TreeNode* deserialize(string data) {
    TreeNode r(data[0] - '0');
    TreeNode* root = &r;
    return root;
}

But this gives me the error "stack use after scope"

I even tried to define root as a member variable to the class where this function is defined and I get "stack buffer overflow".

Here's the definition of TreeNode,

Definition for a binary tree node.
struct TreeNode {
  int val;
  TreeNode *left;
  TreeNode *right;
  TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

Problem #297


Solution

  • Variables only exist in their respective scope. The scope of your variable r is the function deserialize, meaning that the memory automatically allocated on the stack upon entering the function will be deallocated upon leaving it.

    The pointer to this structure you are returning will then be dangling, which means that it will point to uninitialized memory and may no longer be used.

    To solve your problem, you will need this code:

    TreeNode* deserialize(string data) {        
        return new TreeNode(data[0] - '0');
    }
    

    This will allocate the TreeNode instance on the heap and return a pointer to it. It will remain there, until you free it explicitely with delete, which you must do, unless you want your application to leak memory.