关于C#:sprintf_s写入初始化缓冲区时失败

swprintf_s fails when writing to initialized buffer

我正在使用Visual Studio 2010在Windows中用C编写程序。我正在使用swprintf_s函数将格式化的字符串写入wchar_t缓冲区。
尝试写入已初始化的缓冲区时,出现以下错误。

1
Unhandled exception at 0x77b3fbda in svats.exe: 0xC00000FD: Stack overflow.

有时

1
Unhandled exception at 0xfefefefe in svats.exe: 0xC0000005: Access violation.

这是产生访问冲突的代码。

1
2
3
wchar_t wBuff[1024] = L"b";
int test;
test = swprintf_s(wBuff,sizeof(wBuff),L"a%s","test");

和堆栈溢出的代码。

1
2
3
wchar_t wBuff[1024] = L"b";
int test;
test = swprintf_s(wBuff,sizeof(wBuff),L"a%s",L"test");

现在第二段代码已经工作了一次,不知道为什么。

有人知道是什么问题吗?

PS。这些文件没有被加载,有人知道为什么吗?是因为visual studio是32位,而我的操作系统是64位?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\
tdll.dll'
, Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\kernel32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\KernelBase.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\user32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\gdi32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\lpk.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\usp10.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\msvcrt.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\advapi32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\sechost.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\
pcrt4.dll'
, Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\sspicli.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\cryptbase.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\ws2_32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\
si.dll'
, Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\imm32.dll', Cannot find or open the PDB file
'svats.exe': Loaded 'C:\\Windows\\SysWOW64\\msctf.dll', Cannot find or open the PDB file


1
2
3
4
5
int main() {
  wchar_t wBuff[1024] = L"b";
  int test;
  test = swprintf_s(wBuff,_countof(wBuff),L"a%s","test");
}

该代码将代替。如pmg所述,第二个参数应为1024,而不是2048。执行sizeof时,它将返回字节大小。但是,swprintf_s要求缓冲区中可用的字符数。您可以使用_countof,该_countof本质上可以扩展为与您已经建议的相同。