[Solved] Advanced pointer typecasting in C/C++ [closed]


The memory simply contains bytes of data. It is up to you how you interpret this data.

Your buffer may be interpreted as int. For example:

char buffer[] = {1, 2, 3, 4};
int number = *(int *)buffer;

Running the code on an Intel x86 processor would result in number having the value of 0x04030201, as integers are stored as 32bit (4 bytes) little-endian buffers.

Your buffer can also be interpreted as code. The C code return 5; may be compiled into the following x86 assembly code:

mov eax, 5
retn

This code looks in the memory as B8 05 00 00 00 C3

So let’s look on the following example:

char buffer[] = {0xb8, 5, 0, 0, 0, 0xc3};
int number = ((int (*)())(buffer))();

Running this code on an Intel x86 processor (assuming you compile this code without security checks that prevent the execution of data buffers) would result in number having the value of 5; The code casts the pointer to buffer into a pointer to a function with the signature int func_name() and then executes it.

1

solved Advanced pointer typecasting in C/C++ [closed]