使用sscanf遇到Run-Time Check Failure #2错误

下面是一段关于sscanf使用时遇到的小问题:
  1. #include "stdafx.h"
  2. #include <windows.h>
  3. #include <iostream>
  4. using namespace std;
  5. int fun ();
  6. int _tmain(int argc, _TCHAR* argv[])
  7. {
  8.     return fun();
  9. }
  10. int fun ()
  11. {
  12.     char szBuf[] = "10.218.14.115";
  13.     byte a = 0;
  14.     byte b = 0;
  15.     byte c = 0;
  16.     byte d = 0;
  17.     sscanf(szBuf, "%d.%d.%d.%d", &a, &b, &c, &d);
  18.     cout << "a = " << a << "/t" << "b = " << b << "/t" << "c = " << c << "/t" << "d = " << d << endl;
  19.     return 0;
  20. }
出现的错误:Run-Time Check Failure #2 - Stack around the variable 'd' was corrupted.

原因:因为一个%d是一个ini所有该变量占了4个字节的大小,而一个byte只占了1个字节的大小所有出现了这样的错误。

改正:将byte类型修改成int就可以了!

你可能感兴趣的:(使用sscanf遇到Run-Time Check Failure #2错误)