Failure in freeing the heap

-1

I have a Win32 console application. When I run that code it throws this exception nearly 60% of the time.

Unhandled exception at 0x777BC799 (ntdll.dll) in x.exe: 0xC0000374: A heap has been corrupted (parameters: 0x777E8890).

void function(CString &outputStr, const char* name, DWORD64 value){
    outputStr = _T("");
    CString csName(name);
    outputStr.Format(_T("<name=\"%s\" value=\"0x%08x\"/>\n"), csName, value);
}

This is one of the functions where the crash takes place(in the last line). When I see the stacktrace it is somewhat like this:

ntdll.dll!_RtlpHeapHandleError@4()  
ntdll.dll!_RtlpLogHeapFailure@24()  
ntdll.dll!@RtlpLowFragHeapFree@12() 
ntdll.dll!_RtlFreeHeap@12() Unknown
abc.exe!ATL::CWin32Heap::Free(void * p) Line 153    C++
abc.exe!ATL::CAtlStringMgr::Free(ATL::CStringData * pData) Line 107 C++
abc.exe!ATL::CStringData::Release() Line 92 C++
abc.exe!ATL::CSimpleStringT<char,0>::~CSimpleStringT<char,0>() Line 263 C++
abc.exe!ATL::CStringT<char,ATL::StrTraitATL<char,ATL::ChTraitsCRT<char> >       ::~CStringT<char,ATL::StrTraitATL<char,ATL::ChTraitsCRT<char> > >() Line 1295C++

Another block of code where crash happen is

std::string dir = "";
dir = dir + "\\" + "abc";

with a similar stack trace. Earlier by debugging I saw a pattern that the crash occurs only where string manipulation is taking place(CString or std::string). As shown in the stack, the crash is occurring when the Free function is called internally when returning from the function block. Now I don't know why this is happening.

c++
string
windows
win32gui
asked on Stack Overflow Feb 9, 2017 by P3A • edited Feb 9, 2017 by P3A

1 Answer

0

The issue is fixed. Actually I was finding the programData folder using

wchar_t *additionalPath = L"\\SomePath\\SomeMorePath";
wchar_t *appDataPath;
SHGetKnownFolderPath(FOLDERID_ProgramData,
    KF_FLAG_CREATE,
    NULL,
    &appDataPath) == S_OK)

PathAppend(appDataPath, additionalPath);

Now this function allocates sufficient memory to appDataPath and writes the value in it. The PathAppend function internally appends the additionalPath to appDataPath. Since the memory that was allocated to appDataPath was limited, there is a possibility that this function appends the additional string and extends the value beyond the allocated memory. Well this results in heap corruption when that memory is accessed by any other part of code.

answered on Stack Overflow Feb 9, 2017 by P3A

User contributions licensed under CC BY-SA 3.0