Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does casting a pointer 'actually' do under the hood?

Tags:

c

pointers

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?

like image 655
Chris Snow Avatar asked Dec 06 '25 17:12

Chris Snow


2 Answers

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.

like image 80
Serge Ballesta Avatar answered Dec 08 '25 10:12

Serge Ballesta


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)