开发者

C++ 64bit issue

开发者 https://www.devze.com 2022-12-23 04:24 出处:网络
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];

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 bit开发者_如何学Cwise operations for 64bit data is incorrect.

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


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消