Why doesn't this work? (pointers)

Discussion in 'C++' started by Chris Schumacher, Oct 10, 2004.

  1. I wrote the following program to demonstrate an oddity I found in C++.

    #include <iostream>
    using namespace std;


    int main()
    {int *p, *q;
    p = q;
    q = new int;
    *q = 12;
    cout << *p;


    system("pause");
    return 0;
    }


    Your compiler will either give a gibberish answer or crash when you try
    to run this program.
    Here's what I don't understand: p and q are pointing to the same memory
    address. That being said, why can't you access the dynamic variable using
    p as well as q?
    What would happen if you created a new variable using p too? Aren't they
    both pointing to the same memory? Would they overwrite each other?

    Thanks.

    -==Kensu==-
    I actually came across this while working with a homemade linked list.
    You can imagine how frustrating THAT was...
    Chris Schumacher, Oct 10, 2004
    #1
    1. Advertising

  2. On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher <> wrote:
    > q = new int;


    Here new allocates space for an int, and returns the location of the new
    object, so this assignment overwrites any previous value of q. And besides, you
    never initialised the old q, so it was full of garbage even before this line.

    You must find a place to store an int (using new or a variable), then set both
    p and q to point to it. Use

    p = q;

    after the "new" line to do this.

    Turn on warnings in your compiler and it will likely detect the use of
    uninitialised variables.

    --
    Ben Caradoc-Davies <>
    http://wintersun.org/
    Ben Caradoc-Davies, Oct 10, 2004
    #2
    1. Advertising

  3. Chris Schumacher wrote:
    > I wrote the following program to demonstrate an oddity I found in C++.
    >
    > #include <iostream>
    > using namespace std;
    >
    >
    > int main()
    > {int *p, *q;


    Here p and q are initialised and thus point to "random" areas in memory.


    > p = q;




    Here the "random" memory address stored in q is assigned to p.



    > q = new int;



    Here an int is created in the free store and its address is assigned to
    q pointer variable.



    > *q = 12;



    Here the address stored in q is dereferenced, and the int pointed is
    assigned the value 12.



    > cout << *p;



    Here you dereference the "random" memory value assigned to p in the
    beginning, and you read some "random" memory portion of the program,
    invoking undefined behaviour.



    --
    Ioannis Vranos

    http://www23.brinkster.com/noicys
    Ioannis Vranos, Oct 10, 2004
    #3
  4. Chris Schumacher wrote:
    > I wrote the following program to demonstrate an oddity I found in C++.
    >
    > #include <iostream>
    > using namespace std;
    >
    >
    > int main()
    > {int *p, *q;


    1. Both the pointer variables are not initialized.

    > p = q;


    2. You are assigning one of them to the other.

    > q = new int;


    3. You are allotting a chunk of memory and q stores the pointer to that
    location.


    > *q = 12;


    4. You are storing a particular value in the memory pointed to , by q.


    > cout << *p;


    5. (3) and (4) still do not affect p anyway. p is still
    uninitialized and dereferencing it results in UB.

    As Ben had already pointed out, you can do
    the assignemnt 'p = q' after allocating memory for q.
    Otherwise it does not help anyway.

    --
    Karthik. http://akktech.blogspot.com .
    ' Remove _nospamplz from my email to mail me. '
    Karthik Kumar, Oct 11, 2004
    #4
  5. Correction:


    Ioannis Vranos wrote:

    > Here p and q are



    uninitialised


    > and thus point to "random" areas in memory.
    Ioannis Vranos, Oct 11, 2004
    #5
  6. Ben Caradoc-Davies <> wrote in
    news::

    > On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher
    > <> wrote:
    >> q = new int;

    >
    > Here new allocates space for an int, and returns the location of the
    > new object, so this assignment overwrites any previous value of q. And
    > besides, you never initialised the old q, so it was full of garbage
    > even before this line.


    Ah, I see now. Thanks.
    Both of the textbooks I used seemed to gloss over the fact that pointers
    are not initalized during declaration. They made it seem that the new int
    or whatever is placed in the memory location that the variable is pointing
    at when declared.

    Thanks again, to everyone who replied.


    -==Kensu==-
    Chris Schumacher, Oct 11, 2004
    #6
  7. Chris Schumacher

    Mike Wahler Guest

    "Chris Schumacher" <> wrote in message
    news:Xns957EB0A80F370kensuhotmailcom@207.115.63.158...
    > I wrote the following program to demonstrate an oddity I found in C++.


    The 'oddity' is in your code, not the language
    >
    > #include <iostream>
    > using namespace std;
    >
    >
    > int main()
    > {int *p, *q;


    There now exist two pointers, named 'p' and 'q'.
    Neither has a defined, valid value. Any attempt
    to evaluate the value of either will produce
    'undefined behavior' (which means anything can
    happen, from 'appearing to work' to a crash,
    or anything else.

    > p = q;


    Kaboom. Evalution of unintialized object.

    > q = new int;


    Allocates storage sufficient to store a single type
    'int' object, and stores the address of this storage
    in the pointer 'q'.

    > *q = 12;


    Assigns the value 12 to the allocated type 'int' object.

    > cout << *p;


    Kaboom again. Evalution of an ininitialized object.

    >
    >
    > system("pause");
    > return 0;
    > }
    >
    >
    > Your compiler will either give a gibberish answer or crash when you try
    > to run this program.


    According to the definition of the language, it can do absolutely
    anything (or nothing) at all.

    > Here's what I don't understand: p and q are pointing to the same memory
    > address.


    They are not. 'p' doesn't point anywhere. 'q' points to an
    allocated type 'int' object.

    >That being said,


    Saying it doesn't make it so. :)

    >why can't you access the dynamic variable using
    > p as well as q?


    Because 'p' does not point anywhere. (It might 'by accident',
    but officially its value is undefined.)


    > What would happen if you created a new variable using p too?


    You can allocate another 'int' and assign its addres to 'p'.
    If you did, then 'p' would have the same behavior as 'q' (except
    that it would point to a different object.).

    > Aren't they
    > both pointing to the same memory?


    No. Nothing in your code has assigned the address of the
    allocated 'int' to 'p'.

    >Would they overwrite each other?


    Only if you write code to do so.

    > I actually came across this while working with a homemade linked list.
    > You can imagine how frustrating THAT was...


    Yes, I imagine expecting behavior based upon a false assumption
    would be frustrating. :)

    -Mike
    Mike Wahler, Oct 11, 2004
    #7
  8. Chris Schumacher

    Mike Wahler Guest

    "Chris Schumacher" <> wrote in message
    news:Xns957EB9FBE1098kensuhotmailcom@207.115.63.158...
    > Ben Caradoc-Davies <> wrote in
    > news::
    >
    > > On Sun, 10 Oct 2004 22:22:00 GMT, Chris Schumacher
    > > <> wrote:
    > >> q = new int;

    > >
    > > Here new allocates space for an int, and returns the location of the
    > > new object, so this assignment overwrites any previous value of q. And
    > > besides, you never initialised the old q, so it was full of garbage
    > > even before this line.

    >
    > Ah, I see now. Thanks.
    > Both of the textbooks I used seemed to gloss over the fact that pointers
    > are not initalized during declaration.


    That is not a 'fact'. The fact is that objects of automatic
    storage duration are not automatically initialized. Their
    type doesn't matter. Objects with static storage duration
    are automatically initialized (to 0).

    > They made it seem that the new int
    > or whatever is placed in the memory location that the variable is pointing
    > at when declared.


    A definition of a pointer *never* will cause it to point
    anywhere unless you supply an initializer. This is the
    case for a pointer of any storage duration.

    Which textbooks are you referring to?

    -Mike
    Mike Wahler, Oct 11, 2004
    #8
  9. Chris Schumacher

    Mike Wahler Guest

    "Ioannis Vranos" <> wrote in message
    news:1097448661.181043@athnrd02...
    > Chris Schumacher wrote:
    > > I wrote the following program to demonstrate an oddity I found in C++.
    > >
    > > #include <iostream>
    > > using namespace std;
    > >
    > >
    > > int main()
    > > {int *p, *q;

    >
    > Here p and q are initialised


    Uninitialised. (But I'm sure that's what you meant).


    >and thus point to "random" areas in memory.


    They might, they might not. Their values are undefined.

    > > p = q;

    >
    > Here the "random" memory address stored in q is assigned to p.


    1) (The randome 'value' of 'q' might or might not correspond to
    valid memory addresses.

    2) Because of 1), no assignment at all is required to take place.

    > > q = new int;

    >
    > Here an int is created in the free store and its address is assigned to
    > q pointer variable.
    >
    > > *q = 12;

    >
    > Here the address stored in q is dereferenced, and the int pointed is
    > assigned the value 12.
    >
    > > cout << *p;

    >
    > Here you dereference the "random" memory value


    First, this causes the value of 'p' to be evaluted, producing
    undefined behavior. A dereference might or might not happen.
    And if such a dereference did somehow succeed, another evaluation
    of an ininitialized object would happen, resulting again in
    undefined behavior.

    >assigned to p in the
    > beginning, and you read some "random" memory portion of the program,
    > invoking undefined behaviour.


    The entire program's behavior becomes undefined as soon
    as the expression p=q is evaluated.

    -Mike
    Mike Wahler, Oct 11, 2004
    #9
  10. Chris Schumacher

    Mike Wahler Guest

    "Mike Wahler" <> wrote in message
    news:60kad.8648$...
    >
    > "Ioannis Vranos" <> wrote in message
    > news:1097448661.181043@athnrd02...
    > > Chris Schumacher wrote:
    > > > I wrote the following program to demonstrate an oddity I found in C++.
    > > >
    > > > #include <iostream>
    > > > using namespace std;
    > > >
    > > >
    > > > int main()
    > > > {int *p, *q;

    >
    > > > p = q;

    >
    > The entire program's behavior becomes undefined as soon
    > as the expression p=q is evaluated.


    Make that "as soon as the expression 'q' is evaluated the first time"

    -Mike
    Mike Wahler, Oct 11, 2004
    #10
  11. Chris Schumacher

    Ron Natalie Guest

    Mike Wahler wrote:

    > That is not a 'fact'. The fact is that objects of automatic
    > storage duration are not automatically initialized. Their
    > type doesn't matter. Objects with static storage duration
    > are automatically initialized (to 0).
    >

    Actually the "fact" is that POD objects of automatic storage
    duration are not default initialized.
    Ron Natalie, Oct 11, 2004
    #11
  12. Chris Schumacher

    Default User Guest

    Ron Natalie wrote:

    > Mike Wahler wrote:
    >
    > > That is not a 'fact'. The fact is that objects of automatic
    > > storage duration are not automatically initialized. Their
    > > type doesn't matter. Objects with static storage duration
    > > are automatically initialized (to 0).
    > >

    > Actually the "fact" is that POD objects of automatic storage
    > duration are not default initialized.


    Are required to not be? Or not required to be?




    Brian Rodenborn
    Default User, Oct 11, 2004
    #12
  13. Chris Schumacher

    Mike Wahler Guest

    "Default User" <> wrote in message
    news:...
    > Ron Natalie wrote:
    >
    > > Mike Wahler wrote:
    > >
    > > > That is not a 'fact'. The fact is that objects of automatic
    > > > storage duration are not automatically initialized. Their
    > > > type doesn't matter. Objects with static storage duration
    > > > are automatically initialized (to 0).
    > > >

    > > Actually the "fact" is that POD objects of automatic storage
    > > duration are not default initialized.

    >
    > Are required to not be? Or not required to be?


    I see neither a requirement for nor a prohibition of
    it in the standard, so I presume the latter. Which
    of course would mean that code intended to be portable
    should not depend upon default initialization of such
    objects.

    -Mike
    Mike Wahler, Oct 11, 2004
    #13
  14. "Mike Wahler" <> writes:

    > "Default User" <> wrote in message
    > news:...
    > > Ron Natalie wrote:
    > >
    > > > Mike Wahler wrote:
    > > >
    > > > > That is not a 'fact'. The fact is that objects of automatic
    > > > > storage duration are not automatically initialized. Their
    > > > > type doesn't matter. Objects with static storage duration
    > > > > are automatically initialized (to 0).
    > > > >
    > > > Actually the "fact" is that POD objects of automatic storage
    > > > duration are not default initialized.

    > >
    > > Are required to not be? Or not required to be?

    >
    > I see neither a requirement for nor a prohibition of
    > it in the standard, so I presume the latter. Which
    > of course would mean that code intended to be portable
    > should not depend upon default initialization of such
    > objects.


    100% ACK. IMHO it is the best way to initialisize everything by
    hand. Different compilers would solve the problem of default
    initialzation with different ways.

    Kind regards,
    Nicolas
    --
    | Nicolas Pavlidis | Elvis Presly: |\ |__ |
    | Student of SE & KM | "Into the goto" | \|__| |
    | | ICQ #320057056 | |
    |-------------------University of Technology, Graz----------------|
    Nicolas Pavlidis, Oct 11, 2004
    #14
  15. I believe you are misunderstanding the meaning of p = q in the pointer
    world.

    source code reformated
    >int main()
    >{
    > int *p, *q;

    Now p and q are created (not initialized)
    ----- -----
    | p |--->o | q |
    ----- pointing to a -----
    random place | pointing to another
    V random place
    o
    > p = q;

    Now both p and q point to the same random place (the place where q
    points to)

    ----- -----
    | p | | q |
    ----- -----
    | |
    | V
    \----------------------->o

    > q = new int;

    Now q points to a valid place where an int should be placed. Note that
    p still points to the random place q used to point

    ----- ----- -----
    | p | | q |------>| |
    ----- ----- -----
    |
    |
    \----------------------->o

    > *q = 12;

    Now 12 is copied to the new int storage create by new and pointed by q
    ----- ----- -----
    | p | | q |------>| 12|
    ----- ----- -----
    |
    |
    \----------------------->o
    > cout << *p;

    Now it should be clear why the output is garbage or crash. UB as
    others have pointed out.
    > system("pause");
    > return 0;
    >}


    Good luck

    Marcelo Pinto
    Marcelo Pinto, Oct 11, 2004
    #15
  16. Chris Schumacher

    Mike Wahler Guest

    "Default User" <> wrote in message
    news:...
    > Ron Natalie wrote:
    >
    > > Mike Wahler wrote:
    > >
    > > > That is not a 'fact'. The fact is that objects of automatic
    > > > storage duration are not automatically initialized. Their
    > > > type doesn't matter. Objects with static storage duration
    > > > are automatically initialized (to 0).
    > > >

    > > Actually the "fact" is that POD objects of automatic storage
    > > duration are not default initialized.

    >
    > Are required to not be? Or not required to be?


    To be or not to be. :)

    -Mike
    Mike Wahler, Oct 11, 2004
    #16
  17. Chris Schumacher

    Ron Natalie Guest

    Default User wrote:
    > Ron Natalie wrote:
    >
    >
    >>Mike Wahler wrote:
    >>
    >>
    >>>That is not a 'fact'. The fact is that objects of automatic
    >>>storage duration are not automatically initialized. Their
    >>>type doesn't matter. Objects with static storage duration
    >>>are automatically initialized (to 0).
    >>>

    >>
    >>Actually the "fact" is that POD objects of automatic storage
    >>duration are not default initialized.

    >
    >
    > Are required to not be? Or not required to be?


    Are not required to be.
    Ron Natalie, Oct 11, 2004
    #17
  18. Chris Schumacher

    Ron Natalie Guest

    Default User wrote:
    > Ron Natalie wrote:
    >
    >
    >>Mike Wahler wrote:
    >>
    >>
    >>>That is not a 'fact'. The fact is that objects of automatic
    >>>storage duration are not automatically initialized. Their
    >>>type doesn't matter. Objects with static storage duration
    >>>are automatically initialized (to 0).
    >>>

    >>
    >>Actually the "fact" is that POD objects of automatic storage
    >>duration are not default initialized.

    >
    >
    > Are required to not be? Or not required to be?


    The point I was trying to make is that Mike's statement is wrong
    as well. Objects of non-POD class type are required to be default
    initalized. Those of POD type are not. It's one of those gross
    stupidities of the C++ language that initializations are conveniently
    omitted just because C was similarly defective.
    Ron Natalie, Oct 11, 2004
    #18
  19. Chris Schumacher

    Mike Wahler Guest

    "Ron Natalie" <> wrote in message
    news:416adbe3$0$28339$...
    > Default User wrote:
    > > Ron Natalie wrote:
    > >
    > >
    > >>Mike Wahler wrote:
    > >>
    > >>
    > >>>That is not a 'fact'.


    Mike:
    > The fact is that objects of automatic
    > >>>storage duration are not automatically initialized.


    I (apparently unfortunately) used the term 'automatically'
    instead of 'default'.

    > Their
    > >>>type doesn't matter. Objects with static storage duration
    > >>>are automatically initialized (to 0).
    > >>>
    > >>


    Francis:

    > >>Actually the "fact" is that POD objects of automatic storage
    > >>duration are not default initialized.


    The difference between our assertions is that you qualified
    with 'POD' (and I used 'automatic' instead of 'default').

    > >
    > >
    > > Are required to not be? Or not required to be?

    >
    > The point I was trying to make is that Mike's statement is wrong
    > as well.



    Is it really 'wrong', or merely 'incomplete'?

    >Objects of non-POD class type are required to be default
    > initalized.



    I think you're confusing me. What about such an object
    initialized via an argument? (OR do you mean only those
    declarations lacking an initializer?)

    -Mike
    Mike Wahler, Oct 11, 2004
    #19
  20. Chris Schumacher

    Default User Guest

    Ron Natalie wrote:

    > Default User wrote:
    > > Ron Natalie wrote:


    > > > Actually the "fact" is that POD objects of automatic storage
    > > > duration are not default initialized.

    > >
    > >
    > > Are required to not be? Or not required to be?

    >
    > The point I was trying to make is that Mike's statement is wrong
    > as well.



    I was actually asking a genuine question, although I was pretty sure of
    the answer. I get burned every now and then with "things in C++ what is
    different than C". I didn't think there was a prohibition, and as I
    recall some compilers do that in debug mode.



    Brian Rodenborn
    Default User, Oct 11, 2004
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. David Prowak

    Why oh why doesn't my data view work?

    David Prowak, Jan 30, 2004, in forum: ASP .Net
    Replies:
    1
    Views:
    725
    Alvin Bruney [MVP]
    Jan 30, 2004
  2. Mr. SweatyFinger

    why why why why why

    Mr. SweatyFinger, Nov 28, 2006, in forum: ASP .Net
    Replies:
    4
    Views:
    863
    Mark Rae
    Dec 21, 2006
  3. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,766
    Smokey Grindel
    Dec 2, 2006
  4. cerr

    pointers, pointers, pointers...

    cerr, Apr 7, 2011, in forum: C Programming
    Replies:
    12
    Views:
    657
  5. Sara
    Replies:
    6
    Views:
    249
    John W. Krahn
    Apr 12, 2004
Loading...

Share This Page