Say I have the following c code:
int* vector = (int*)malloc(5 * sizeof(int));
malloc returns a void pointer because doesn't know what is being asked to allocate space for.
Therefore, we are casting the void pointer to an int pointer.
Does the cast actually do anything at runtime, or is it just required for compiling? If it does work at runtime, what is it doing?
Answer
Casting of pointers is required at compile time with the notable exception of pointers to void that may be converted to or from pointers to any type without explicit cast.
What happens at run-time is not specified by the language with the exception that pointer to char and pointer to void are required to have same representation. For what remains, the only thing required is (6.3.2.3 Conversion / Pointers § 7) A pointer to an object or incomplete type may be converted to a pointer to a different
object or incomplete type. If the resulting pointer is not correctly aligned for the
pointed-to type, the behavior is undefined. Otherwise, when converted back again, the
result shall compare equal to the original pointer
But on common architectures, the representation of a pointer to any object is the address of its first byte. So pointer conversion at runtime is a no-op.
No comments:
Post a Comment