Save pointer's memory address

Viewed 21079

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 *)?

5 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.

char buf[32] = {0}
snprintf(buf, sizeof buf, "%p\n", s);

then you can print it:

printf("%s\n", buf);

You've already saved the value as a bit pattern in s, so I assume you mean that you simply want the text output by printf as a string. The call you want is sprintf:

char text[255];
sprintf(text, "%p\n", s);

If you want the pointer address returned from your function, you can declare your function to return the pointer type:

int* myFunc(int n) {
  int* p;
  p = malloc(n*sizeof(int));
  // more stuff
  return p;
}

This is an alternative to the use of sprintf as suggested (very reasonably) by other answers.

Take your pick.

Note that on some systems an int would not be big enought to hold a int* data type - using int* is not only clearer but safer as well.

Yes sprintf() is the best option. Here you can simply take any thing inside a string.

Related