what does the following type casting do in C? -
i have question type casting in c:
void *buffer; (int *)((int)buffer);
what type casting doing? , ((int)buffer)
doing?
imagine on linux/x86-64 computer mine. pointers 64 bits , int
32 bits wide.
so, buffer
variable has been initialized location; perhaps 0x7fff4ec52020 (which address of local variable, perhaps inside main
).
the cast (int)buffer
gives int, least significant 32 bits, i.e. 0x4ec52020
you casting again (int*)((int)buffer)
, gives bogus address 0x000000004ec52020 not point valid memory. if dereference bogus pointer, you'll sigsegv.
so on machines (notably mine) (int *)((int)buffer)
not same (int*)buffer
;
fortunately, statement, (int *)((int)buffer);
has no visible side effect , optimized (by "removing" it) compiler (if ask optimize).
so such code huge mistake (could become undefined behavior, e.g. if dereference pointer). if original coder intended weird semantics described here, should add comment (and such code unportable)!
perhaps #include
-ing <stdint.h>
, using intptr_t
or uintptr_t
make more sense.
Comments
Post a Comment