The call to sprintf in the posted code is printing 8 characters to a 1 character buffer. The buffer overrun has corrupted the stack. The destination buffer should be at least 9 characters, 8 for the text and 1 for the null terminator.
I get the error (stack around the variable buf was corrupted) after the message box, how do I fix it?

Ahmed Osama
120
Reputation points
How do I fix the error (stack around the variable "buf" was corrupted)
The code:
if (HIWORD(wParam) == BN_CLICKED && LOWORD(wParam) != IDM_ABOUT && LOWORD(wParam) != IDM_EXIT) {
GetWindowTextA(hWndEdit, &fin[0], 64300);
GetWindowTextA(hWndEdit2, &scin[0], 64300);
if (scin == (LPSTR)"") {
ShellExecuteA(NULL, "runas", &fin[0], NULL, NULL, SW_SHOWNORMAL);
}
else {
ShellExecuteA(NULL, "runas", &fin[0], &scin[0], NULL, SW_SHOWNORMAL);
}
if (GetLastError() != 0) {
char buf;
sprintf(&buf, "%08x", (int)GetLastError());
std::string res(&buf);
DWORD le = GetLastError();
std::string message = (std::string)"APC Administrative Application Execution Utility encountured an error of code 0x" + res + ": " + "\"" + std::system_category().message(GetLastError()); +"\"";
int lastError = GetLastError();
std::wstring hexerror = L"0x" + WCHAR(DecToHex(GetLastError()));
const char* HEs = message.c_str();
MessageBoxA(hWnd, LPCSTR(message.c_str()), "APC Administrative Application Execution Utility", MB_ICONERROR);
}
It says:
Run-Time Check Failure #2 - Stack around the variable 'buf' was corrupted.
Image:
How to fix this problem and without causing errors?
Accepted answer
It should be &buf[0] or otherwise it would write to something after the string (because of it writing at something after the beginning) causing errors
exactly 8 bytes after the variable
It can be -
In C/C++ the above syntax passes the address of the dest array.
You should give consideration to using the secure versions of CRT functions that take buffer lengths as a parameter. Refer to https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/sprintf-s-sprintf-s-l-swprintf-s-swprintf-s-l?view=msvc-170
Sign in to comment