Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store a memory address in an integer?

This is exactly the same question title as found here - I would also like to store a memory address in a variable - or rather, a void* in a variable. However, I'd rather store it in some form of an int rather than a string, as I'd like to cast it back to a pointer afterwards.

This is because it is a member of a class that I would then like to serialize with boost serialize, and if I did use a void*, boost serialize might try to store what the pointer is pointing to, which wouldn't be very sensible in my case.

I need this for 32 and 64 bit gcc and MSVC, so basically I was wondering whether there was an inbuilt integer type that was the size of pointers on the same platform. Alternatively, I guess I would need to IFDEF my own type?

like image 727
Cookie Avatar asked Nov 05 '12 15:11

Cookie


People also ask

Is a memory address an integer?

The main memory (or simply the memory) is where variables and other information are stored while a program runs. From the perspective of a program, the computer's memory is a collection of bytes, each with an integer address.

Can I store address in int?

You can do it, but it's not portable. On an x86-64 architecture, for example, a pointer occupies 64 bits, but an int is only 32 bits wide. If you try to store a pointer in an int, truncation will occur.

How do you store a memory address?

Storing the value of the pointer (i.e. the memory location of some variable) in a string can be done much like you've used printf: char buf[128]; void *s = malloc (size); sprintf(buf, "%p\n",s);

Is an address an integer C++?

An address is a non-negative integer. Each time a program is run the variables may or may not be located in same memory locations.


1 Answers

intptr_t and uintptr_t are integer types that are large enough to hold a void*. They are defined by C++11 in <cstdint> and by C99 in <stdint.h>

If uintptr_t is not available, you could try uintmax_t, defined in the same header(s) or by Boost in <boost/cstdint.hpp>.

like image 164
Fred Foo Avatar answered Oct 26 '22 10:10

Fred Foo