使用memset出现的一个错误

来源:互联网 发布:新加坡动物园门票 淘宝 编辑:程序博客网 时间:2024/06/06 16:26

今天在调试一个大数运算的程序时,出现了很诡异的事情:一些相对较小的数据运算是正确,而当数据到达一定位数的时候,运算结果中高位的某些位数据出现了错误。在进行单元测试的时候已经保证了此大数运算算法的正确性,所以错误肯定发生在别的地方。最后在调试中,终于发现错误出在了下面这条语句中:
memset(res,0,sizeof(res)/sizeof(res[0]));// clear the res buffer

我们先看一下库函数memset的用法:
void * memset ( void * ptr, int value, size_t num );
Fill block of memory
Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Parameters
ptr
    Pointer to the block of memory to fill.
value
    Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num
    Number of bytes to be set to the value.
Return Value
ptr is returned.
Example

res是一个可以存放150个int类型数据的数组。memset是把res空间的前n个字节设置为某一具体的数值。而在我的程序中,memset(res,0,sizeof(res)/sizeof(res[0]));实际上是把res空间的前sizeof(res)/sizeof(res[0])=数组中元素的个数个字节的设置为了0,然而按照程序的需求,正确的做法应该是将res数组全部设置为0,因此正确的代码应该是:

// clear the res buffer
memset(res,0,sizeof(res));// 注意:第三个参数是将res的首 n 个字节的值设为值 0,不是数组元素的个数sizeof(res)/sizeof(res[0])
所以上面诡异的情况其实就是因为res的高位字节没有被及时清空为0,所以才会出现错误。修改之后,程序结果正确。


原创粉丝点击