It is not returning a pointer to counter
. That would be &counter
, which is a pointer to a local variable. Doing that would be an error because local variables are destroyed as soon as the function returns, so the caller would be left with a pointer to a thing that no longer exists.
In practice, counter
probably lives on the stack or in a register (or several registers). The code segment is usually read-only, so variables couldn't live there.
(void *)counter
is converting a number to a pointer value. The results of that operation are implementation-defined.
For example, with gcc:
A cast from integer to pointer discards most-significant bits if the pointer representation is smaller than the integer type, extends according to the signedness of the integer type if the pointer representation is larger than the integer type, otherwise the bits are unchanged.
The resulting address may not be a valid pointer value at all, or it may point to an unmapped page.