Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save pointer's memory address

I have to implement a function that returns the memory address of a pointer when I allocate it with malloc(). I know that malloc(value) allocates an area on the heap which is of size value.

I know how to implement the code for printing the memory address of that pointer:

    void *s = malloc (size)
    printf("%p\n",s);

My question is, how can I save the value printed by that code in an int or string (e.g. char *)?

like image 371
horro Avatar asked Dec 05 '13 19:12

horro


People also ask

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);

How can pointer saves memory space?

Pointers save memory space. Execution time with pointers is faster because data are manipulated with the address, that is, direct access to memory location. Memory is accessed efficiently with the pointers. The pointer assigns and releases the memory as well.

Where is the address of a variable stored?

The address of a local variable isn't stored anywhere, unless you have a pointer pointing to the local variable. The local variables themselves are typically stored on the stack on most modern systems.


1 Answers

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);

To 'save' the value into an integer (type) you can do a simple cast:

void *s = malloc (size);
size_t int_value = (size_t)s;

Since in c you never know what your machine address pointer length is, this (technically) isn't guaranteed to work quite right; both of these methods can go wrong with wacky architectures or compilers.

like image 187
Rooke Avatar answered Sep 16 '22 15:09

Rooke