1

I'm studying for a test and one of the questions was to implement a system like valgrind for Windows. My fellow students and I were interested in doing the following:

void* ptr = malloc(size);
int ptr_location = (int)ptr;
free( (void*) ptr_location);

The reason is to easily manage memory by locations and sizes in a map, instead of holding the pointer itself.

Are these conversions legal, and is there a better way to do this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Blue Granny
  • 772
  • 1
  • 8
  • 24

2 Answers2

3

It is implementation defined behavior.

Quoting C11, chapter §6.3.2.3/p6,

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

Rather, you can use intptr_t or uintptr_t, which are described in §7.20.1.4, as (available in <stdint.h>)

[...] type designates a(n) (un)signed integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

Not sure what you're asking but generally the above example is wrong and non-portable as int size and void * may differ on various platforms.

If you really want to cast void * to some int type, it's better to use intptr_t (or uintptr_t) which are guaranteed to have (at least) the same size as void *.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
  • intptr_t is a pointer or a number? As if how would I use the type intptr_t – Blue Granny Jul 18 '16 at 08:07
  • 1
    @ArikRinberg it is a number. One usage would be to replace `int` in your example by `intptr_t`. It is just a special integer type to hold pointers. –  Jul 18 '16 at 08:14