user3707950
user3707950

Reputation:

What is happening in this code? reinterpret_cast<int*>(buf)

It seems to me that the buffer is being modified. Does it put 6 integers and then 5 floats into the buffer? It's also strange that they set size to 44 instead of 1024*sizeof(char). Perhaps the whole buffer is passed to write() but write() writes only the first 44 bytes to the client.

Could you please explain line by line? I have no experience with c++.

char buf[1024];
int* pInt = reinterpret_cast<int*>(buf);
*pInt = 5;
*(pInt+1) = 2;
*(pInt+2) = 3;  
*(pInt+3) = 4;
*(pInt+4) = 5;
*(pInt+5) = 6;

float* pFloat = reinterpret_cast<float*>(pInt+6);
*pFloat = 111;
*(pFloat+1) = 222;
*(pFloat+2) = 333;
*(pFloat+3) = 444;
*(pFloat+4) = 555;

int n;
int size = (1+2*5)*4;
n = write(buf, size);

Upvotes: 0

Views: 106

Answers (1)

R Sahu
R Sahu

Reputation: 206717

Does it put 6 integers and then 5 floats into the buffer?

Yes.

It's also strange that they set size to 11 instead of 1024*sizeof(char)

They don't want to write the entire buffer. Thy want to write just the ints and floats that were written to the buffer.

FWIW, that is poorly written code. It assumes that sizeof(int) and sizeof(float) are both equal to 4. A more portable method would use:

int size = 6*sizeof(int) + 5*sizeof(float);

Caution

Even though the posted code might work under some, perhaps most, circumstances, use of

int* pInt = reinterpret_cast<int*>(buf);
*pInt = 5;

is cause for undefined behavior by the standard. It violates the strict aliasing rule. There wasn't an int to begin with at that location.

Had you used:

int array[5] = {};
char* cp = reinterpret_cast<char*>(array);

// ...

int* iptr = reinterpret_cast<int*>(cp);
*iptr = 10;

there would be no problem since cp points to a place where an int was there to begin with.

For your use case, it will be better to use:

char buf[1024];
int intArray[] = {5, 2, 3, 4, 5, 6};
std::memcpy(buff, intArray, sizeof(intArray));

float floatArray = {111, 222, 333, 444, 555};
std::memcpy(buff+sizeof(intArray), floatArray, sizeof(floatArray));

int n;
int size = sizeof(intArray) + sizeof(floatArray);
n = write(buf, size);

Further reading:

  1. reinterpret_cast creating a trivially default-constructible object
  2. Unions and type-punning

Upvotes: 6

Related Questions