0

the public pointer member get assigned a strange value every time any function gets called.. it's not the constructor called because then the value should be changed or at least the pointer address should change pointer directs to the same address but the value changes what happened?

class whathappened {
public:
    int * a;
    whathappened();
    void print();
};

whathappened::whathappened() {
    int b = 23;
    a = &b;
}

void whathappened::print() {
    cout << a << " " << *a << endl;
}

int main() {
    whathappened sam;
    cout << sam.a << " " << *sam.a <<  endl;
    sam.print();
    cout << sam.a << " " << *sam.a << endl;
    while (1) {}
}

0133F650 23
0133F650 -858993460
0133F650 -858993460

3 Answers3

5

The pointer a in your example points to a value that goes out of scope after the constructor. The pointer itself remains unchanged, but the value is likely overwritten by other values on the stack as more functions are called.

Tyler
  • 51
  • 1
  • 3
1

Anytime returning a reference to local function object will cause undefined behavior,so as pointer(in most cases).

standard N4727- 6.6.3/7

after the lifetime of an object has ended and before the storage which the object occupied is reused or released, any glvalue that refers to the original object may be used but only in limited ways....The program has undefined behavior if: 1.the glvalue is used to access the object 2.....

In your example,it's called a dangling pointer.The a actually stores a pointer which points to a stack address,and during the function call or stack unwinding,the content you point to is always changing,depends on the current stack frame.

If any pointer is pointing the memory address of any variable but after some variable has deleted from that memory location while pointer is still pointing such memory location. Such pointer is known as dangling pointer and this problem is known as dangling pointer problem.

And about reference:

Although references, once initialized, always refer to valid objects or functions, it is possible to create a program where the lifetime of the referred-to object ends, but the reference remains accessible (dangling). Accessing such a reference is undefined behavior.

choxsword
  • 3,187
  • 18
  • 44
0

If you allocate b on heap then the behavior will be expected, like

whathappened::whathappened() 
{
   int *b = new int(23); 
   a = b;
}

OR, you can just do

whathappened::whathappened() 
{
   a = new int(23); 
}

In this case no worry about the scope of b. By assigning a = b we have told a to point the memory which is on heap. And that will be valid till we don't call delete on a. To release the memory pointed by a you need to call delete. like

whathappened::~whathappened() 
{
    delete a;
}
Swapnil
  • 389
  • 5
  • 22