tags:

views:

109

answers:

4
+1  Q: 

C++ 64bit issue

I have the following code:

tmp_data = simulated_data[index_data];
unsigned char *dem_content_buff;
dem_content_buff = new unsigned char [dem_content_buff_size];
int tmp_data;
unsigned long long tmp_64_data;

if (!(strcmp(dems[i].GetValType(), "s32")))
{
    dem_content_buff[BytFldPos] = tmp_data;
    dem_content_buff[BytFldPos + 1] = tmp_data >> 8;
    dem_content_buff[BytFldPos + 2] = tmp_data >> 16;
    dem_content_buff[BytFldPos + 3] = tmp_data >> 24;      
}

if (!(strcmp(dems[i].GetValType(), "f64")))
{
    tmp_64_data = simulated_data[index_data];
    dem_content_buff[BytFldPos] = tmp_64_data;
    dem_content_buff[BytFldPos + 1] = tmp_64_data >> 8;
    dem_content_buff[BytFldPos + 2] = tmp_64_data >> 16;
    dem_content_buff[BytFldPos + 3] = tmp_64_data >> 24;
    dem_content_buff[BytFldPos + 4] = tmp_64_data >> 32;
    dem_content_buff[BytFldPos + 5] = tmp_64_data >> 40;
    dem_content_buff[BytFldPos + 6] = tmp_64_data >> 48;
    dem_content_buff[BytFldPos + 7] = tmp_64_data >> 56;
}       

I am getting some weird memory errors in other places of the application when the second if statement is true and executed. When I comment out the 2nd if statement, the problem works fine. So I suspect the way I am performing bitwise operations for 64bit data is incorrect.

Can anyone see anything in this code that needs to be corrected?

+1  A: 

It looks fine—from what I can see. It would be a good idea to have BytFldPos range checked before executing.

wallyk
+1  A: 

I would check that dem_content_buff_size is large enough for the 64-bit numbers and also that BytFldPos+7 always lies within the array bounds.

Peter Alexander
A: 

Each element of the dem_content_buff array is an unsigned char . You're assigning into each such element a long long. Is this your intent?

If not, it could lead to data corruption as that conversion will (or can) lose value.

James D
+2  A: 

I would suspect an interaction between dem_content_buff_size and BytFldPos. If the following is not true:

assert(dem_content_buff_size > (BytFldPos + 7));

then you are going to overflow your buffer.

R Samuel Klatchko