1

How is this allowed in C?

int p= (int) malloc (sizeof(int));

I only get a warning when I compile in gcc.

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

A void pointer cannot be casted to a primitive type right?

*((int*)(x))//is allowed - assume x is of type void*

But how is direct cast to primitive also allowed?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Varun Rao
  • 393
  • 1
  • 5
  • 19

1 Answers1

4

This is not forbidden, but implementation defined behaviour. Quoting C11, chapter §6.3.2.3

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.

That is why compiler emits the warning.

That said, quoting chapter 7.20.1.4, Integer types capable of holding object pointers, we have intptr_t and uintptr_t.

The following type designates a 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:

intptr_t

The following type designates an unsigned 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:

uintptr_t


Having said that, just for sake of completeness's sake, let me add that, there is fair amount of reasons on why not to cast the return value of malloc() and family in C..

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