swprintf_s fails when writing to initialized buffer
I am writing a program in C for windows using visual studio 2010. I am using the swprintf_s function to write a formatted string to a wchar_t buffer. I am getting the following errors when I attempt to write to a buffer that has been initialized.
Unhandled exception at 0x77b3fbda in svats.exe: 0xC00000FD: Stack overflow.
and sometimes
Unhandled exception at 0xfefefefe in svats.exe: 0xC0000005: Access violation.
Here is the code that produces the access violation.
wchar_t wBuff[1024] = L"b";
int test;
test = swprintf_s(wBuff,sizeof(wBuff),L"a%s","test");
and the code for the stack overflow.
wchar_t wBuff[1024] = L"b";
int test;
test = swprintf_s(wBuff,sizeof(wBuff),L"a%s",L"test");
Now the 2nd piece of code worked once, don't know why.
Anyone know what the problem is?
PS. These files aren't getting loaded, anyone know why? Is it because visual studio is 32 bit and my OS is 64 bit?
'svats.exe': Loaded 'C:\Windows\SysWOW64\ntdll.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
'sva开发者_开发百科ts.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\rpcrt4.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\nsi.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
int main() {
wchar_t wBuff[1024] = L"b";
int test;
test = swprintf_s(wBuff,_countof(wBuff),L"a%s","test");
}
This code would work instead. As stated by pmg, the second parameter should be 1024, not 2048. When you do sizeof, it will return the size in bytes. However swprintf_s
expects the number of characters available in the buffer. You can either use _countof
which essentially expands to the same as what has already been suggested to you.
精彩评论