Address location in integer form back to pointer

Viewed 243

I am trying to figure out if its possible to take the integer address of an integer in memory, and cast it back to an actual pointer. Below is an example. My eventual goal, and maybe im overcomplicating the problem is I have a pointer to a very large object in memory. I need to share the pointer/data to other threads and the only mechanism I have in place (legacy system) is to communicate with uint8_t[8] arrays. So I was going to take the pointer address, convert it to an int, split it into a byte array, transmit, and re-assemble it on the other end.

#include <stdint.h>
int main() {
  /* Test value to see if code works */
  uint64_t value = 123;
  /* Get the pointer to the value, this is what we will working with */
  uint64_t* value_ptr = &value;
  /* Get the integer value of the address/memory location, this is what I am 
    try to cast back into a pointer to 'value' */
  uint64_t value_adr_int = &value_ptr;
  /* Some time later we want to get back to value_ptr. 
    This is the piece not working */
  uint64_t* cast_value_ptr = (uint64_t*)value_adr_int;
  /* Test to make sure our newly casted pointer points to the original int */
  if (*cast_value_ptr == value) {
    /* Print success */
  }
  
}

Edit: Answer thanks to Daniel was changing the one line to:

uintptr_t value_adr_int = (uintptr_t)value_ptr;
1 Answers

You're setting value_adr_int to &value_ptr. That would mean that value_adr_int holds the value of a uint64_t** instead of a uint64_t* which is what you want. You need to remove the &.

On another note, you should use uintptr_t, which was added (I believe) in C99. It is an integer type designed for this exact situation. It is perfectly safe to cast pointers to uintptr_t and back.

Related