CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    [RESOLVED] Simple question - mem addresses

    Hello everyone - just registered and thought someone might be able to explain something to me.
    I'm back in school which I should have ten years ago but I'm finishing what I didn't. Fun so far.

    In the 2nd quarter of programming and we are learning c++. 1st quarter was a breeze. 2nd quarter has killed me getting in to pointers, templates, exception handling (that was easy), classes, etc. The more powerful tools of the language.

    Right now I am screwing around to teach myself the next weeks readings. Linked lists.

    I'll get it but here is what I am questioning.

    If you look at the attached code I thought if I made head a pointer, made current a pointer, both pointing to the same stucture that when I checked the memory address, they would both be the same but they are not.

    Now maybe I have been up to late and not doing something right (obviously I am not).

    address of head is 0x28ff44
    address of current is 0x28ff40
    (addresses in my system obviously)

    I thought that since both head and current are pointers to the same thing the address would be the same.

    This is not a school assigment. I like to write little scripts to sort of see how things work, I seem to understand things better this way. Play around.

    PS - Thank you and not sure if we are to past code on the forum so I did the attached file.
    Attached Files Attached Files

  2. #2
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    Re: Simple question - mem addresses

    Stupid me -
    Code:
    struct llNode // linked list nodes
    {
    	int numbers;	// ints in the link list
    	llNode *next;	// the reference to the next node
    } 
    nodeStruc;
    
    int main()
    {
    llNode *current, *head; // initializes llnode type
    current = head;
    //llNode *current; //new pointer to allow us move, but not lose the original head
    cout << "Address of the head is: "<<&head<<endl;
    cout << "Address of the pointer current: "<<&current<<endl;
    cout <<"Enter a number that will go in the 1st postion of the list:";
    cin >> nodeStruc.numbers;
    cout << "number enterd: "<<nodeStruc.numbers<<endl;
    cout << "number var address: "<<&nodeStruc.numbers<<endl;
    current->numbers;
    cout << "head pointer address: "<< &head<<endl;
    cout << "current pointer address: "<<&current<<endl;

  3. #3
    Join Date
    Aug 2008
    Posts
    902

    Re: Simple question - mem addresses

    Why would current and head have the same address? They are two different variables, what they point to is irrelevant. I think you are mistakenly using the address-of operator when you don't mean to.

  4. #4
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Simple question - mem addresses

    Sure, you can paste code into your posts but doing so it should be within code tags [code]Paste your code here[/code]. You can read about other formatting tags here http://www.codeguru.com/forum/misc.php?do=bbcode

    You say that you have made both current and head point to the same thing but you haven't done that. At the moment they are only declared and without being initialized/assigned they point to a random memory location.

    When you print them you also print the address to the pointer itself, not the content of it, that's why they differ.

    If you change to
    Code:
    llNode* current = &nodeStruc;
    llNode* head = &nodeStruc;
    remove the NULL assignment and drop the & from the printout you will see that they have the same content.

    These things are by the way easy to view using the debugger. You posted in the Non Visual C++ forum (which is correct) but if you actually use MSVC you have an excellent debugger to play around with.

    Edit: You found the code tags by yourself! That doesn't happen often for new members!
    Last edited by S_M_A; February 18th, 2012 at 06:29 AM.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Simple question - mem addresses

    Quote Originally Posted by mm12463 View Post
    I like to write little scripts to sort of see how things work,
    Please, do not call C++ programs "scripts". You are writing a program, not a script.
    I seem to understand things better this way. Play around.
    OK, but remember that std::list does everything you're trying to do.

    http://www.cplusplus.com/reference/stl/list/

    If you want to write an application, where one of the entities uses a linked list, you don't need to write your own, as one exists already. So either you can get bogged down in low-level details, or learn C++ at a higher level and use constructs that are standard, proven to work, and get the job done faster.

    Having said this, I don't think you're going to get far unless you know how to manipulate pointers first. If you don't have an understanding of pointers, dynamically allocated memory, etc., then you're not going to get too far with your "project".

    For example, simple things like this indicate you need to learn or relearn how to use pointers correctly:
    Code:
    llNode *current, *head; // initializes llnode type
    current = head;
    current and head are uninitialized. So setting one to the other does absolutely nothing as the values of those pointers are garbage. You also have other very basic mistakes that have been mentioned so far by other posters.

    IMO, you should not be tackling something such as linked list unless you know the basics first -- you need a solid grounding in pointers, pointer manipulation, knowing how to debug pointer issues, dynamic memory allocation and properly deallocating the memory, etc.

    Once you know these things, then you would be ready to write your own data structures. But as I stated before, if you really want to write a real application, and the application uses linked lists to store data, then go with the std::list.

    Regards,

    Paul McKenzie

  6. #6
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    Re: Simple question - mem addresses

    Chris_F- Your right. I am looking at the address of the pointer in mem and not the info or link that it is pointing too. Think I am saying the correctly. My idea was to make sure they both had the same link info. For eg head has a link of 3000 which is the location of node 1. So if head is 3000, current should show the same info. Then I would know they are pointing to the same info. Just my way of checking things and make sure I am on the right path - which obviously I am not.


    S_M_A - When I read your reply I wanted to shoot myself. I cannot stay up for almost 20hrs and try to learn something and write a small program that will me understand things when I am a walking zombie. Specifically the pointers not be initialized. Thank you.

    Paul - I apologize for calling it a script. I am writing programs. I am taking your advice to heart. I am going to go back over the next few days and reread and make sure I get a better understanding of what you mentioned like pointers. At times I swear what I did well a week ago went right out the door this week.

    I won't lie - this quarter has been pretty tough for me. Taking this class online is not fun since you are on your own pretty much. Unfortuantly it was my only option to keep on schedule and fit in with work and the other classes. Nightmare but I know people have a lot more on their plate and manage to do well.

    Far as std::list. We don't even touch a lot of them for another 4 weeks. I think the idea of why we are do it this way right now, is to expand on our previous knowledge of pointers, classes, structures, templates and what not and keep building on those. Not 100&#37; sure but seems to be the flow of the book.

    You guys are great and if you lived near me, I'd buy you dinner and then bribe you for personal tutoring! LOL. Thank you. I am sure I will be around from time to time if not asking questions, reading a lot more on the forum.

  7. #7
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    Re: Simple question - mem addresses

    For me I find working code helps me understand what the book is telling us. Sometimes the books IMO, just don't allow me to visualize it well so I have to take some time and create a small program. Although not perfect it did help me understand pointers when we learning that 4 weeks ago but did not use again for a few weeks. Makes it hard to retain when you do not use it alot or keep building on it.

    Code:
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main(){
    
    int *p;
    int q=5;
    p = &q;
    cout << "The program is doing this:\n";
    cout <<"int *p;\n";
    cout <<"int q=5;\n";
    cout <<"p = &q;\n";
    cout << setfill('-')<<setw(25) << "-\n";
    cout <<"So when we run a few things here is what happens:\n";
    cout << "Value of int q is: " << q <<endl;
    cout << setfill('-')<<setw(25) << "-\n";
    cout << "Mem. address of q by doing '&q' but not really useful.\n";
    cout << "q is a variable, not a pointer.\n";
    cout << "q address is: "<< &q <<endl;
    cout << setfill('-')<<setw(25) << "-\n";
    cout << "p is: " << p << " the address the pointer p is pointing to, the address of q.\n";
    cout << "&p is: " << &p << " the address the p by doing &p.\n";
    cout << "*p is pointing to q so when using *p we get the value of q: " << *p <<endl;
    delete p;
    cout << setfill('-')<<setw(25) << "-\n";
    cout << "After 'delete p;' and doing 'cout  p' the output of p is now: " << p << " the mem. address of p"<< endl;
    cout <<"On my system the pointer p is still showing the memory space it was pointing to."<<endl;
    cout << setfill('-')<<setw(25) << "-\n";
    cout <<"Now to do it better we set the pointer to NULL after the \n";
    cout <<"delete opertion with 'p= NULL;'."<<endl;
    p = NULL;
    cout << "After 'delete p; p=NULL;' the output of p is now: " << p <<endl;
    cout <<"The mem. address that p is pointing to which does not exist. Hence is its zero"<< endl;
     
          return 0;
    
    }
    Does make sense or am I completely wrong here?
    That could be my problem if I am using this as my guide and why I would have troubles.
    Last edited by mm12463; February 19th, 2012 at 12:58 AM. Reason: spelling

  8. #8
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Simple question - mem addresses

    Code:
    delete p;
    The address that p points to was not retrieved by calling new, therefore you never call delete on such an address. Your program now will exhibit undefined behaviour after that call to delete. On some systems, that "delete" would have crashed your program.

    The rule is simple, you only call delete on memory that was allocated using new. The only exception is if the pointer is NULL, as calling delete on a NULL pointer is harmless.

    Also, this cout doesn't print what p is pointing to:
    Code:
    cout << "After 'delete p;' and doing 'cout  p' the output of p is now: " << p << " the mem. address of p"<< endl;
    The correct (but still invalid code -- see next paragraph) is this:
    Code:
    cout << "After 'delete p;' and doing 'cout  p' the output of p is now: " << *p << " the mem. address of p"<< p << endl;
    You must dereference what p points to to see the data.

    However, there is a big bug in doing this -- even if you did allocate with new, and then called delete, there is no guarantee what the stuff that p points to will contain. It could be the same data before the delete call, it could be all wiped out with 0xFF or NULLs, who knows. What is known is that you can't use p to refer to the data after the delete call, unless you point p to another valid address (or call new again and p points to that memory location).

    This means that dereferencing a "deleted" pointer is undefined behaviour. Again, your program may crash if you executed that line I gave, even with the "corrections" I mentioned.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; February 19th, 2012 at 11:47 AM.

  9. #9
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Simple question - mem addresses

    A minor comment regarding the "q is a variable, not a pointer".

    Both p and q are variables. One being an int, one being a pointer to an int. Try to avoid thinking of pointer variables different than any other variable.

    What environment do you use? If you use MS Developer Studio I do believe it will be of great help running this in the debugger. Using the watch window you can view these things without the need to print out anything. Just type the thing you want to view in it (like &p, *p, &q and so on).

    One thing will probably confuse you though. When running a MS debug build dynamic memory is handled in a special way to assist the debugging. An un-initialized variable will for instance have the value 0xCCCCCCCC. See for instance this link http://www.codeguru.com/Cpp/W-P/win3...cle.php/c9535/ for the values used by the MS debug libraries.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  10. #10
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    Re: Simple question - mem addresses

    Interesting to learn about delete. Not one thing was mentioned in the book about this or with a program I wrote and turned in a month ago. No comment about using that the same way. Lesson learned. Thank you.

    I do see where you talked about undefined behaviour. The more I play around I can see how after the delete sometimes I will get the value of q (which is 5)even though I deleted that reference of the pointer p to the variable q.

    I'm going to rewrite this so it is correct and using the advice you shared with me. I'm learning.

    You guys are a lot of help. Things like algebra are cake walk compared to learning a language like C++.

    I'm installing MS Visual Studio 2010 ultimate now. Going to start using that. Downloading the 1gb of updates for it. Fun. Thank god for high speed cable. lol

    I am currently using Bloodshed Dev-C++ 4.9.2 and have since I took my the first class in October. Got comfortable with it and didn't bother to download MS Visual Studio. Should have. It's free since I'm a student.

    Debugger would be nice - Bloodshed debugger isn't that great or I just suck at getting it to work. Sort of gave up on it.
    -Mike

  11. #11
    Join Date
    Oct 2006
    Location
    Sweden
    Posts
    3,654

    Re: Simple question - mem addresses

    As far as I know Bloodshed isn't maintained anymore so dropping it for something newer is a good choice. I don't know how to work with the Bloodshed IDE but you might to have to learn some new things when switching to MSVC.

    I would say that the most common issues for a beginner are that the default project settings use pre-compiled headers and builds for unicode.
    Debugging is twice as hard as writing the code in the first place.
    Therefore, if you write the code as cleverly as possible, you are, by
    definition, not smart enough to debug it.
    - Brian W. Kernighan

    To enhance your chance's of getting an answer be sure to read
    http://www.codeguru.com/forum/announ...nouncementid=6
    and http://www.codeguru.com/forum/showthread.php?t=366302 before posting

    Refresh your memory on formatting tags here
    http://www.codeguru.com/forum/misc.php?do=bbcode

    Get your free MS compiler here
    https://visualstudio.microsoft.com/vs

  12. #12
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Simple question - mem addresses

    Code:
    Right now I am screwing around to teach myself the next weeks readings. Linked lists.
    I'm always confused as to why the implementation of linked lists is taught so early in C++ courses.

    Whilst, of the face of it, linked lists are simple in concept, the proper implementation of one that supports all of the facilities a user would expect (insertion, deletion, swapping elements, sorting, etc) nearly always turns out to be an extremely difficult task for a novice programmer to get right.
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  13. #13
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Simple question - mem addresses

    Quote Originally Posted by JohnW@Wessex View Post
    Code:
    Right now I am screwing around to teach myself the next weeks readings. Linked lists.
    I'm always confused as to why the implementation of linked lists is taught so early in C++ courses.

    Whilst, of the face of it, linked lists are simple in concept, the proper implementation of one that supports all of the facilities a user would expect (insertion, deletion, swapping elements, sorting, etc) nearly always turns out to be an extremely difficult task for a novice programmer to get right.
    I think it is just to get a hands on understanding of pointers. There are few other tasks that'll test if you understand pointers quite as well. If you can write a "kind of working" linked list, then you understand pointers. I've never seen any teacher ask for the all out templated-iterator oriented-reusable implementation; they just want a write and forget implementation.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  14. #14
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Simple question - mem addresses

    I could understand that, but all so often we get students here trying to get their heads round trying to add insert and delete methods to their 'simple' linked list class and getting thoroughly confused, especially with respect to head/tail nodes when empty vs not-empty.
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  15. #15
    Join Date
    Feb 2012
    Location
    Minneapolis, MN USA
    Posts
    8

    Re: Simple question - mem addresses

    Brian - Think you are correct about bloodshed too. A while back I was trying to figure out how its debugger work and I kept coming on statements like it is broken and the entire thing is not being maintained. So using the new MS visual studio will take some learning but probably better in the end.

    ...hands on understanding...
    I think this entire class for both quarters is getting our hands on and obtain a basic understanding of how programming is done and the methods and process to writing a succesful program. Even if it is very basic.

    ...extremely difficult task for a novice programmer to get right...
    I wouldn't call me a novice - I would put it a lot lower then that! Sub-Sub-Novice.

    I would say a lot of the topics from classes, pointers, linked lists have so far been my biggest challenge. Hard to grasp the ideas at times and visualize it in my head. Even the idea of inheritance in classes drove me up a wall.

    Not the idea, but implementing it so that it actually makes sense to use it. At least in my head. Sure an animal is the base, dog, cow, rhino are the derived classes. But to me the part I hard time getting was what the heck can be really basic piece(s) of data in an animal that the derived classes can be built on. Things like that caught me and still do.

    What I had to realize is we had been taught how to use them and the assignments were more about making sure we know how to create and use them in our program. Even if it did not make the most logical sense it was can "Mike access the dervied classes, pull the data from the derived class and base class to complete the assignment." Least that is my thinking.
    -Mike

Page 1 of 2 12 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured