Thread: Printing out the memory address

  1. #1
    Registered User
    Join Date
    Jan 2007
    Posts
    4

    Printing out the memory address

    Hi, how can I get the actual memory address (f.instance 0x0800h) where my variables are stored and my pointers are pointing?

    I'd like to print the address to the screen using cout.

  2. #2
    Registered User rynoon's Avatar
    Join Date
    Dec 2006
    Location
    London, ON
    Posts
    26
    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int iVal1 = 32;
        cout << &iVal1 << endl;
    
        int* ptrVal2 = new int(128);
        cout << ptrVal2 << endl;
    
        delete ptrVal2;
    
        return 0;
    }
    Last edited by rynoon; 01-07-2007 at 04:35 PM.
    Courage, my friends; 'tis not too late to build a better world. - Tommy Douglas

  3. #3
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    If the pointer points to char, you have to cast it to a void*, though, else it's interpreted as a string.
    Code:
    const char *ptr = "some literal";
    std::cout << static_cast<void*>(ptr) << std::endl;
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  4. #4
    Registered User
    Join Date
    Jan 2007
    Posts
    4
    Thanks for your replies.

    The reason I'm asking it that I've written a class, Monitor, which behaves kinda like cout. Today I'm able to do this:
    Code:
    Monitor mon;
    int number = 123;
    mon << "A long string";
    mon << number;
    but when I do this:
    Code:
    Monitor mon;
    char* msg = "A long string";
    mon << "Address of msg is: ";
    mon << &msg;
    I get an "error: invalid conversion from 'char**' to 'int'" when I try to compile, so I guess I need to create a Monitor& Monitor::operator<<(char**) function as well, but I'm uncertain how to write it so that the address is printed.

    Part of my Monitor class looks like this:
    Code:
    Monitor& Monitor::operator<<(char *data)
    {
    	while (*data != 0)
    	{
    		if (*data == '\n') //new line
    		{
    			while(this->characterPosition < 80) //Insert whitespaces until we are at end of line
    			{
    				PutCharacter(' ');
    			}
    			//data++;
    		}
    		else if(*data == '\t') //tabulator
    		{
    			int tabulatorSize = 4;
    			while(tabulatorSize--)
    				this->PutCharacter(' ');
    		}
    		
    		this->PutCharacter(*data);
    		data++;
    	}
    	
    	return *this;
    }
    I've also got a function Monitor% Monitor::operator<<(int data), so I can print integers.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    Given your function, it would just be
    mon << msg;

    > while(this->characterPosition < 80)
    How does this loop exit, given that nothing changes inside the loop which could ever make it false.

    > while(tabulatorSize--)
    Mmm, if I have
    " \tHello"
    and
    "\tHello"
    I would normally expect the two Hellos to be lined up.
    Tabs are a bit more complicated than a simple replacement with 4 (or however many) spaces.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Jan 2007
    Posts
    4
    Quote Originally Posted by Salem
    Given your function, it would just be
    mon << msg;
    That just outputs the actual characterstring "A long string", while I'm interrested in the address where the string is stored. I'd like to print for example 0x0203940. I tried to do
    Code:
    mon << &msg;
    and have written a function like this
    Code:
    Monitor& Monitor::operator<<(char** data)
    {
        this->PutCharacter('0');
        this->PutCharacter('x');
        while (**data != 0)
        {
            this->PutCharacter(**data);
            **data++;
        }
    }
    but I'm still not able to output the actual address.

    Quote Originally Posted by Salem
    > while(this->characterPosition < 80)
    How does this loop exit, given that nothing changes inside the loop which could ever make it false.
    In the function PutCharacter I write a single char to the screen, and increment the characterPosition. So I get out of the loop eventually.

    Quote Originally Posted by Salem
    > while(tabulatorSize--)
    Mmm, if I have
    " \tHello"
    and
    "\tHello"
    I would normally expect the two Hellos to be lined up.
    Tabs are a bit more complicated than a simple replacement with 4 (or however many) spaces.
    You're right, I need to change that one so that it jumps to the first characterPosition which is dividable by 4. F.instance, if at position 38, I need to jump to position 40. Thanks!

  7. #7
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by Scalpel78
    That just outputs the actual characterstring "A long string", while I'm interrested in the address where the string is stored. I'd like to print for example 0x0203940. I tried to do
    Code:
    mon << &msg;
    and have written a function like this
    Code:
    Monitor& Monitor::operator<<(char** data)
    {
        this->PutCharacter('0');
        this->PutCharacter('x');
        while (**data != 0)
        {
            this->PutCharacter(**data);
            **data++;
        }
    }
    but I'm still not able to output the actual address.
    The answer was already given by CornedBee: cast to void*.

    I've heard that some implementations of ostream don't overload void*, though. For those you might try casting to unsigned long*.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  8. #8
    Registered User
    Join Date
    Jan 2007
    Posts
    4
    Quote Originally Posted by dwks
    The answer was already given by CornedBee: cast to void*.
    Ok, using
    Code:
    mon << (void*)msg
    requires me to make a function in Monitor with prototype
    Code:
    Monitor& Monitor::operator<<(void*)
    {
        //What to put here?
    }
    but then I'm very uncertain as to what the implementation needs to be.

    Let me also note, that I'm not using the standard library (I'm playing around with OS development and is developing EVERYTHING from scratch. That's why I need my own cout replacement), so I don't have the static_cast function.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    I guess one way is to cast your void* to an unsigned long, then do whatever you did for your int function, but using base 16 rather than base 10.

    Though this is far from being portable if you're doing it all yourself.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    static_cast isn't a function. It's an operator. Not having it is like not having the '+' operator or the array index operator '[]'.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    So what you want to know is how to convert a void* into a readable representation, right?

    Salem gave you the right idea, but unsigned long is a dangerous type to use: it will fail, for example, on 64-bit Windows using the MS compiler.

    Personally, I'd just use sprintf.
    Code:
    #include <climits> // Contains CHAR_BITS, I think.
    #include <cstdio>
    
    Monitor& Monitor::operator<<(void *ptr)
    {
        char buffer[sizeof(ptr) * ((CHAR_BITS + 3) / 4) + 1]; // A buffer that is guaranteed to be large
            // enough to hold the hex representation of a pointer, plus a NUL.
        std::sprintf(buffer, "%p", ptr);
        return (*this) << buffer;
    }
    This allows you to avoid worrying about finding an integral type the same size as a pointer, which is not exactly trivial unless you accept non-portable code.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  12. #12
    Registered User
    Join Date
    Jun 2004
    Posts
    201
    to format to hexadecimal immediately:

    std::cout << std::hex << (void *)pointer << std::endl;

  13. #13
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Laserve
    to format to hexadecimal immediately:

    std::cout << std::hex << (void *)pointer << std::endl;
    The question was how to implement this operator in its own class, not how to use with the cout
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  14. #14
    Registered User
    Join Date
    Jun 2004
    Posts
    201
    Quote Originally Posted by vart
    The question was how to implement this operator in its own class, not how to use with the cout
    o rly, lets see

    Hi, how can I get the actual memory address (f.instance 0x0800h) where my variables are stored and my pointers are pointing?

    I'd like to print the address to the screen using cout.
    maybe next time I wont try to be helpful :P

  15. #15
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Quote Originally Posted by Laserve
    o rly, lets see

    maybe next time I wont try to be helpful :P
    Maybe next time you will read a little bit futher when just the first post in the thread?
    The reason I'm asking it that I've written a class, Monitor, which behaves kinda like cout. Today I'm able to do this:
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Asking windows for memory on a fixed address
    By pheres in forum Windows Programming
    Replies: 4
    Last Post: 03-23-2009, 11:15 AM
  2. Pointer to specific memory address
    By elnerdo in forum C++ Programming
    Replies: 10
    Last Post: 05-19-2006, 07:35 AM
  3. how to get memory address applied in other program?
    By wu7up in forum C Programming
    Replies: 1
    Last Post: 03-01-2003, 01:44 AM
  4. Memory address?
    By Munkey01 in forum C++ Programming
    Replies: 4
    Last Post: 02-01-2003, 09:04 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM