Stop around xyz variable has been corrupted

I am trying to get a simple piece of code that I found on a website to work in VC ++ 2010 on Vista 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 compiles, 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 this: "C \ 0: \ 0 \ 0U \ 0s \ 0e \ 0r \ 0s [...]" - I wonder where everything comes from these files.

  • My friend compiled it on windows xp 32 (also VC ++ 2010) and can run it without problems

any hints / tips / opinions?

thanks

+4
source share
2 answers

The dock is not very clear. The returned string is WCHAR, two bytes per character are not one, so you need to allocate twice as much space, otherwise you will get a buffer overflow. Try:

 BOOL result; WCHAR oldWallPaper[(MAX_PATH + 1)]; result = SystemParametersInfo(SPI_GETDESKWALLPAPER, _tcslen(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)

+4
source

Each Windows feature has 2 versions:

 SystemParametersInfoA() // Ascii SystemParametersInfoW() // Unicode 

A version ending in W is a version of the wide character type function (i.e., Unicode). All the \ 0 you see is because each character you return is in Unicode - 16 bytes per character - the second byte is 0. Therefore, you need to save the result in a wchar_t array and use wprintf instead of printf

 wchar_t oldWallPaper[MAX_PATH]; result = SystemParametersInfo(SPI_GETDESKWALLPAPER, MAX_PATH-1, oldWallPaper, 0); wprintf( L"Current desktop background is %s\n", oldWallPaper ); 

So you can use version A SystemParametersInfoA() if you are not using Unicode. However, you should always use Unicode for recording.

Typically, SystemParametersInfo() is a macro that evaluates the version of W if UNICODE is defined on your system.

+3
source

Source: https://habr.com/ru/post/1309685/


All Articles