views:

145

answers:

1

hi,

I'm trying to get some simple piece of code I found on a website to work in VC++ 2010 on windows vista 64:

#include "stdafx.h"
#include <windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
 DWORD dResult;
 BOOL result;
 char oldWallPaper[MAX_PATH];

 result = SystemParametersInfo(SPI_GETDESKWALLPAPER, sizeof(oldWallPaper)-1, oldWallPaper, 0);

 fprintf(stderr, "Current desktop background is %s\n", oldWallPaper);

 return 0;
}

it does compile, but when I run it, I always get this error:

Run-Time Check Failure #2 - Stack around the variable 'oldWallPaper' was corrupted.

I'm not sure what is going wrong, but I noticed, that the value of oldWallPaper looks something like "C\0\:\0\0U\0s\0e\0r\0s[...]" -- I'm wondering where all the \0s come from.

  • A friend of mine compiled it on windows xp 32 (also VC++ 2010) and is able to run it without problems

any clues/hints/opinions?

thanks

+2  A: 

The doc isn't very clear. The returned string is a WCHAR, two bytes per character not one, so you need to allocate twice as much space otherwise you get a buffer overrun. Try:

 BOOL result; 
 WCHAR oldWallPaper[(MAX_PATH + 1)]; 

 result = SystemParametersInfo(SPI_GETDESKWALLPAPER, sizeof(oldWallPaper), &oldWallPaper, 0); 

See also:

http://msdn.microsoft.com/en-us/library/ms724947(VS.85).aspx

http://msdn.microsoft.com/en-us/library/ms235631(VS.80).aspx (string conversion)

Ade Miller
This is the correct answer.Also, this is C++, not C. std::wcerr << L"Current desktop background is " << oldWallPaper;
DeadMG
thanks a lot, guys!
tirolerhut
lz_prgmr