Home > Back-end >  Clion warning "The address of the local variable may escape the function"
Clion warning "The address of the local variable may escape the function"

Time:01-05

I just have started learning C and am trying to work with binary tree. I cannot find an answer if should I fix this warning "The address of the local variable may escape the function"? I have class BinaryTree. This class has two pointers BinaryTree * left = nullptr; and BinaryTree * right = nullptr; Also my class has method void BinaryTree::randomTree(bool grow, bool actDepth, short maxDepth, short depth = 0)

From very beginnig I make empty tree

BinaryTree tmpTree = BinaryTree(
                minDepth,
                mProbability,
                cProbability
        );

Then I want to grow this tree

        tmpTree.randomTree(
                (bool) Helper::fiftyFifty(),
                (bool) Helper::fiftyFifty(),
                Helper::getRandomNumber(minDepth, maxDepth   1)
        );

And I have a warning in randomTree method

... some code ...
        BinaryTree lTmpTree = BinaryTree(
                this->minDepth,
                this->mProbability,
                this->cProbability
        );
        this->left = &lTmpTree;  // <---- I have warning there

        this->left->randomTree(grow, actDepth, maxDepth, depth   (short) add);
... some code ...

Tell me please if I should be worried about this warning?

CodePudding user response:

It's a scope issue. You make a local variable, lTmpTree, which will get destroyed when you exit local scope.

You're taking a reference to that local variable, though

this->left = &lTmpTree;

which is dangerous because, as mentioned at the top, lTmpTree gets destroyed when you leave local scope. This means the bits for lTmpTree might still exist correctly in memory if they haven't been re-allocated for something else, but you can't count on it. This is why you get the warning.

  • Related