RMCampos
RMCampos

Reputation: 21

Print the content of a memory address typed by user in C++

How can I print the address typed by the user? This way don't work.

This is the code. Thanks.

#include <iostream>

using namespace std;

int main()
{
    int num = 123456;
    int *addr = &num;

    cout << "Var: num, address: " << &num << ", has: " << num << endl
         << "Var: *addr, address: " << &addr << ", has: " << addr << endl
         << "Printing value of num using the pointer *addr: " << *addr << endl;

    int addr_user;
    cout << "Type the memory address: "; cin >> addr_user;

    int *p_addr_user = (int *)addr_user;

    cout << "The address given (" << addr_user << ") has: " << *p_addr_user << endl;
    return( 0 );
}

Sorry, I was not so clear:

What the program must to do: ask to type an integer, print the memory address from those integer, ask to type the memory address printed above, print the content of that memory address and confirm if that address has the number typed in step one.

All in one runtime. Thank you in advance.

Upvotes: 0

Views: 1129

Answers (1)

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

I tried this out in Linux:

g++ q.cpp 
q.cpp: In function ‘int main()’:
q.cpp:17:31: warning: cast to pointer from integer of different size [-Wint-to-pointer-    cast]
./a.out
Var: num, address: 0x7fff562d2828, has: 123456
Var: *addr, address: 0x7fff562d2818, has: 0x7fff562d2828
Printing value of num using the pointer *addr: 123456
Type the memory address: 0x7fff562d2828 
Segmentation fault (core dumped)

So I notice a couple of issues:

  1. I Naturally want to try to put in the address of num, but it is displayed in hex
  2. Seg fault

To input in hex I change the input line to:

cout << "Type the memory address: "; cin >> hex >> addr_user;

(otherwise it is interpreted as 0)

But it is still segfaulting.

Here's the problem:

int *p_addr_user = (int*)addr_user;

Oh, there was a warning about it above. Sometime about different sizes (also note that pointers are unsigned.)

ints and pointers can be different sizes (it depends on your platform) For me int is 32 bit and pointers are 64 bit.

Here's how I got it working:

#include <stdint.h>
#...
uintptr_t addr_user;
cout << "Type the memory address: "; cin >> hex >> addr_user;
uintptr_t *p_addr_user =(uintptr_t*) addr_user;   

Upvotes: 1

Related Questions