0

Can someone explain to me why, in the Push_Back function, the values of a structure are erased?

class Lista2
{
public:
    typedef struct Element
    {
        Element(int newValue)
        {
            value = newValue;
            next = nullptr;
        }

        Element* next;
        int value;
        Element* prev;
    };
    Element* first;

    void init() {
        Element ok(0);
        first = &ok;
    }

    void Push_Back(int value)
    {
        Element* temp = first;
        Element* temp2;
        temp2 = new Element(value);
        if (temp != nullptr)
        {
            while (temp->next != nullptr)
            {
                temp = temp->next;
            }
            temp->next = temp2;
        }
        else first = temp2;
    }

I called the function: init() and after Push_Back(). In Push_back I see this in debuger:

Can someone explain to me why, in the Push_Back function, the values of a structure are erased?

  • 1
    The life-time of local variables ends when the block they were defined in ends. In the case of the `ok` variable in the `init` function, once the function ends the variable ceases to exist. Any saved pointer (or reference) to it will become invalid. Attempting to dereference such a pointer leads to *undefined behavior*. Please take some time to refresh about life-time and scopes in your text-books. – Some programmer dude Mar 22 '22 at 15:48
  • `temp->next` is `0xCCCCCCCC`, you should probably initialize your `next` **and** `prev` pointers to `nullptr` in the constructor for your `Element` class. You also likely want that constructor to be `explicit` (you probably don't want to be able to assign or cast an integer to an Element) – Wyck Mar 22 '22 at 15:50

1 Answers1

0

In init, you created variable on stack, took it address and saved it as the structure member.

AgainPsychoX
  • 1,527
  • 1
  • 16
  • 20