最近碰到的一个关于memcpy的奇葩问题


最近写代码,碰到一个奇葩问题,memcpy函数用起来,编译居然提示我stackoverflow,简直是对写C的码农的最大羞辱,WTF!

    UINT8 numBuffers = 0;
    UINT16 cpLength = 0;
//  TPM2B_DIGEST *bufferList;
    if(length%(MAX_DIGEST_BUFFER) != 0)
        numBuffers = length/(MAX_DIGEST_BUFFER) + 1;
    else
        numBuffers = length/(MAX_DIGEST_BUFFER);

    TPM2B_DIGEST *bufferList[numBuffers];
    for(UINT8 i = 0; i < numBuffers; i++)
    {
        (bufferList)[i] = (TPM2B_DIGEST *)calloc(1,sizeof(TPM2B_DIGEST));
        if(i < numBuffers-1)
        {
//          memcpy(bufferList[i]->t.buffer, &buffer[cpLength], MAX_DIGEST_BUFFER);
            for( UINT16 m = 0; m < MAX_DIGEST_BUFFER; m++)
            {
                bufferList[i]->t.buffer[m] = buffer[m + cpLength];
            }
            cpLength = i * MAX_DIGEST_BUFFER;
        }
        if(i == numBuffers-1 )
        {
            for(UINT16 j= 0; j < (length-cpLength); j++)
            {
                bufferList[i]->t.buffer[j] = buffer[cpLength + j];
            }
        }

    }

就是上面注释掉的
memcpy(bufferList[i]->t.buffer, &buffer[cpLength], MAX_DIGEST_BUFFER);

编译的时候,结果如下:

In file included from /usr/include/string.h:639:0,
                 from tpm2_sign.cpp:61:
In function ‘void* memcpy(void*, const void*, size_t)’,
    inlined from ‘int computeDataHash(BYTE*, UINT16, TPMI_ALG_HASH, TPM2B_DIGEST*)’ at tpm2_sign.cpp:669:73:
/usr/include/x86_64-linux-gnu/bits/string3.h:53:71: error: call to void* __builtin___memcpy_chk(void*, const void*, long unsigned int, long unsigned int) will always overflow destination buffer [-Werror]
   return __builtin___memcpy_chk (__dest, __src, __len, __bos0 (__dest));

自查半天,没觉得有什么错,网上查了半天,居然查到一个“GCC Bugzilla – Bug 37060”,翻到最后跟我说是“fixed in GCC 4.7.0”

链接在此   GCC Bugzilla -Bug 37060


我gcc -v 查自己的gcc版本, 妈蛋, 都4.9.2了啊,我勒个去。

只好折衷,选个别的办法解决问题,一位位的复制吧,不用memcpy了。


            for( UINT16 m = 0; m < MAX_DIGEST_BUFFER; m++)
            {
                bufferList[i]->t.buffer[m] = buffer[m + cpLength];
            }


尼玛,现在还没弄明白,到底是个神马情况,有时间好好扒一扒这家伙的老底,奶奶个腿儿的,先记下来!


你可能感兴趣的:(C/C++,TPM)