Home > Software design >  Is the same memory allocated to all objects of class
Is the same memory allocated to all objects of class

Time:01-20

I was trying to build a linked list without allocating memory dynamically. Note that I can build linked list using new operator. The below code does not work. When I debugged it I found out (as much as I can understand) that Node a(n, head) is allocated at the same address in the memory every time so the a stores pointer to itself. If someone can explain to me, it would be of great help.

class Node {
public:
    int val;
    Node *next;
    
    Node(int n, Node *ptr = NULL) {
        val = n;
        next = ptr;
    }
};

class LinkList {
    Node *head = NULL;
public:
    void insertNode(int n) {
        Node a(n, head);
        head = &a;
    }
    void print() {
        Node* ptr = head;
        while (ptr != NULL) {
            cout << ptr->val << endl;
            ptr = ptr -> next;
        }
    }
};

int main() {
    LinkList a;
    a.insertNode(3);
    a.insertNode(4);
    a.print();
    return 0;
}

CodePudding user response:

No, the same memory is not allocated to all objects of a class... but the same memory is allocated for the local variables of every function. Once a function returns, all its local variables are destroyed, so its local variable memory is now unused, and the next function call will use it for its local variables. Hence every time you call insertNode it uses the same memory to hold a. And when you call print, it uses that same memory to hold ptr.

This is just what usually happens. Not all compilers do it the same way, so you can't rely on it. And if you had extra function calls between main and insertNode then insertNode's variables wouldn't get the same addresses as they do when main calls insertNode directly.

Also note that because you aren't allowed to use pointers to variables that were already destroyed, the optimizer is allowed to guess that when you use a pointer, it points to a variable that hasn't been destroyed, and sometimes this causes really weird behaviour. So you mustn't use pointers to destroyed variables, ever, even if you would be okay with getting the wrong data. The technical term is undefined behaviour.

  • Related