Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I store a 64-bit memory address in a variable?

Tags:

c

pointers

I need to store a 64-bit memory address in a variable, a long should be large enough to hold such value.

For example:

long arr[2];

//store the memory address of arr[1] in arr[0]
arr[0] = (long)(arr + 1);

printf("arr[0]: 0x%012x Actual address: %p\n", arr[0], (void *)arr);

Output:

arr[0]: 0x00007c6a2c20, Actual address: 0x7ffe7c6a2c20

The value stored in arr[0] seems to be truncated.

What am I missing here?

like image 203
fourth_and_29 Avatar asked Oct 15 '25 12:10

fourth_and_29


2 Answers

If you want to store a 64 bit values, you can use uint64_t type of variable.

However, since the values you want to store are addresses, probably you need to use uintptr_t, make sure the available size of that type in your platform and you can use that.

like image 183
Sourav Ghosh Avatar answered Oct 17 '25 02:10

Sourav Ghosh


What you are missing is that %x expects an unsigned int, but on your particular implementation an address appears to be an unsigned long, so use %lx instead.

Note that technically this is undefined behaviour, so always use %p in production code as depending on architecture the underlying size of a pointer may change.

like image 44
Ken Y-N Avatar answered Oct 17 '25 02:10

Ken Y-N