printf() seems to change a variable

I'm a cpp beginner and have trouble to understand why, in the following code, the printf()... function seems to change some variables. Is something wrong in the code, or in my compiler instalation?

#include <iostream>
#include<stdio.h>

class Node
{
public:
    int val;
    Node * next;

    Node(int v) { // constructor
        val=v;
        next=NULL;
    }
};

class Stack
{
public:
    Node *head;
    Stack(int i) // constructor
    {
        Node n(i);
        head=&n;
    }
};

int main() 
{
    Stack s(1);
    printf("s.head->next: %p\n",s.head->next);
    printf("s.head->next: %p\n",s.head->next);
}

I get the following output:

s.head->next: 00000000
s.head->next: FFFFFFFE

How is that possible that I don't get the same? (I got similar problems when using the std:cout function instead, but the minimal code would be longer). Thanks for the feedback.

1 answer

  • answered 2017-06-17 19:54 Neil Butterworth

    This:

      Node n(i);
    

    creates a local variable, that you then store the address of:

      head=&n;
    

    and use that address later.

    After that, all bets are off, as you are in undefined behaviour land.