what does casting a pointer 'actually' do under the hood?
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?
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.
Casting a pointer could do something nontrivial. However, typically pointers of any type to a particular address all have the same representation, so the cast doesn't do anything.
That said, that is only if the code is implemented at face value; all sorts of crazy things can happen with optimization, so that the machine code comprising your executable doesn't directly correspond to the source code. (of course, in that case, there still probably isn't anything correspond to the cast)
The cast doesn't do anything at runtime. It's used at compile time to let the compiler know that you do in fact intend on treating one data type as another.
A void *
is special, because in C (but not C++) you're allowed to assign any (non-function) pointer to or from a void *
without the compiler warning you about it.
Because of this, you should never cast to or from a void *
, as you're doing in your example. In the case of malloc
doing so can mask the fact that you forget to #include <stdlib.h>
, which can lead to some subtle bugs elsewhere in your code.
上一篇: 理解和实现malloc
下一篇: 什么确实在铸造一个指针?