使用sscanf_s时,变量周围的堆栈已损坏

时间:2014-05-11 15:15:01

标签: c visual-studio-2010 scanf unsigned-integer

我安静地不明白为什么我会收到错误“堆栈变量”tmp“已损坏”。

我在不同的函数中使用相同的代码并且它运行良好但是现在当函数“返回”它会抛出上面提到的错误。

struct frame {
   uint8_t dst[6]; 
   uint8_t src[6];    
};

//fill frame.dst || src exactly same way as code below without any errors or warnings

bool fcn() {

    uint8_t tmp[6];

    sscanf_s("00-00-00-00-00-00", "%x-%x-%x-%x-%x-%x", &tmp[0], &tmp[1], &tmp[2], &tmp[3], &tmp[4], &tmp[5]);
    //here I compare tmp[0] == frame.mac[0]...
    return true; 
} //here pops the error while debugging

我在程序的不同部分使用完全相同的代码,但没有错误。

2 个答案:

答案 0 :(得分:2)

%x说明符写入int参数,但您正在将指针传递给uint8_t。由于int是您平台上较大的类型,因此在写出这些字段时会覆盖内存。传递指向int的指针,并根据需要将它们转换为您需要的类型。

您也希望在使用此代码的任何地方执行此操作!

答案 1 :(得分:2)

参考 C-Standard确认系统:

要在32位机器上扫描8位值,需要使用"hh"长度修改器。 32的一半的一半是8


对于VC,需要使用变通方法扫描到unsigned int s。