# Access Violation or Heap Corruption Exception after Windows Library Call

### Question

• I am getting an access violation or heap corruption exception when trying to run a WinRT Console application. I was able to recreate the problem in a simple example. After creating a new C++ WinRT console application in Visual Studio 2017, replace the source code in Program.cpp with the below code, and append an #include "windows.h" in pch.h. (Kindly gloss over the use of calloc() and free() instead of new and delete. I'm coming from C.)

#include "pch.h"
// #include "windows.h" has been added to pch.h.

using namespace winrt;

int main()
{
LPCWSTR path = L"c:\\path\\to\\some\\file.txt";
LPWSTR buffer = (LPWSTR) calloc(255, sizeof(char));
int size = GetFullPathName(path, 255, buffer, 0);

/*
Comment out all the following calls, and the program will exit
successfully. Comment out zero, one, or two of the following calls, and
the program will throw an access violation or heap corruption exception
on one of the calls or at the end of the function.

Alternatively, comment out the GetFullPathName call, above, leave the
following lines active, and the program will exit successfully.
*/
wprintf(L"Press Enter to continue:");
getchar();
free(buffer);
}


The application builds, but when you try to run it in Visual Studio, an access violation or heap corruption exception gets thrown on one of the function calls after the large comment block. This has been reproduced on two separate machines.

I am hoping I am overlooking something obvious. But what that is eludes me.

Tuesday, June 11, 2019 3:55 PM

• You are mixing WCHAR and char, nevermind the rest.

buffer is 127.5 wchars, but you say it's 255.

Tuesday, June 11, 2019 9:32 PM

### All replies

• You are mixing WCHAR and char, nevermind the rest.

buffer is 127.5 wchars, but you say it's 255.

Tuesday, June 11, 2019 9:32 PM
• Indeed, that was it. Hopefully the mistake is the same in the original code.

Thanks!

Tuesday, June 11, 2019 9:57 PM