3

I'm not good at advanced C++ scripts. I have tried to find out more about the following variable assignments without success. Please explain them or give me a source to study similar statements.

rand_seed = *(int*)input_buffer_ptr;
moving_input_ptr = (BYTE*)((int*)input_buffer_ptr + 1);
1
  • The first expression is quite simple: extract the first item of input_buffer_ptr pointer after int * cast. The rand_seed shall be an 'int`. Commented Dec 10, 2016 at 22:05

1 Answer 1

2

(Considering that int is 4 bytes)

Imagine RAM as a long line of bytes (because it is):

RAM: .... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....

and SOME_TYPE* as the pointer on some byte:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
           ^
      input_buffer_ptr

int* means that you treat data under this pointer as integer (number of size 4 bytes)

So if you have pointer SOME_TYPE* input_buffer_ptr

(int*)input_buffer_ptr; // casts this pointer to int*, 
     //so now you treat data under this pointer as 4 bytes integer

then:

*(int*)input_buffer_ptr; // operator * before pointer gets data under 
          //that pointer, in this case, integer (4 bytes).

So rand_seed is integer and has value:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
           |      random_seed     |

Then:

     (int*)input_buffer_ptr + 1
//    ^                     ^
// casting to int*      moving pointer to size of int (4 bytes)

So:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
                                   ^
                         ((int*)input_buffer_ptr + 1)

And then:

 (BYTE*)((int*)input_buffer_ptr + 1);
// ^
// casting pointer to BYTE*, so it points to the same place
// but now treated as one byte pointer.

so if you try this:

BYTE a = *(BYTE*)((int*)input_buffer_ptr + 1);

you will get one byte variable with value:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
                                   |  a  |
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the great detailed answer @Yevhen Kuzmovych.
Note: this is undefined behaviour (strict aliasing violation) unless the buffer was originally written via int also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.