-2

What's the difference between the two ways of creating a structure?

No.1 is right, and No.2 gives the error:

reference binding to misaligned address 0x63775f5f00676e6f for type 'const int', which requires 4 byte alignment

What's the difference between the two ways of creating a structure?

What did the No.2 do?

Here is my codes.

Thank you.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {     
        if (preorder.size() == 0 || inorder.size() == 0)
            return nullptr;

        // # 1
        // struct TreeNode *RootTree = new TreeNode(preorder.front());

        // # 2
        struct TreeNode RootNode(preorder.front());
        struct TreeNode *RootTree = &RootNode;

        return RootTree;
    }    
};
Guodong Hu
  • 303
  • 1
  • 2
  • 11

1 Answers1

2

One problem with #2 is that you’re returning the address of an object with automatic storage, whose lifetime ends as soon as the function returns. That is undefined behavior. The standard says that the compiler is entitled to assume you won’t do that, so anything can happen. If you aren’t getting a warning or error message at compile time, turn on more warnings. (On gcc or clang, -Wall -Wextra -Wpedantic -Wconversion at least.) The address of an object created with new is valid, but must be manually deleted.

Either return a TreeNode and rely on copy elision to make the code efficient, or return a std::unique_ptr<TreeNode> to manage the object’s lifetime for you.

Davislor
  • 14,674
  • 2
  • 34
  • 49