Pointer points to wrong memory location

When while and cin involved , this question becomes so vague to me .
If I don't use cin or anything else here ,just new int and pointers , everything is fine !
Help me understand please ,thanks :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 #include <iostream>
using namespace std;

int main()
{

    int *p = new int ; //somewhere on the heap 
    int temp ;

    while (cin >> temp) /*this overloaded operator returns istream object ,
        where is it stored ? How do I know its accurate address ?*/
    {
        *p = temp ;
        p ++ ;        // arbitrary times loops , break the loop using Ctrl + Z on Windows 
    }
    p--;   // move pointer to the last memory location which has valid value.
  
    cout << *p ;  //why it points to garbage ?
    delete p ; //destroy the pointer on the stack .
}
Last edited on
so... ¿how many numbers did you input?
12
23
121
21
7
^Z
7 //This is a sample input and output using my code :
Process returned 0(0x0) ...
//Weird ...it works perfectly again ....
@ne555 ,Are you from Spain or Latin American ? I love the upside down ? ,Haha .
I input 5 ~ 10 numbers usually . but this time it turned out to be okay ,I am even more confused .....:(

This program should print out the last number you entered .
Last edited on
this overloaded operator returns istream object ,
where is it stored ? How do I know its accurate address ?
It returns the provided istream left of the operator >>. In this case cin. So it is absolutely reliable.

When you modify p (p++ / p--) it will be out of bounds because you provided only memory for a single int. So any access to a value of p that is not the original value will lead to undefined behavior / probably crash.
Topic archived. No new replies allowed.