free heap block modified after it was freed
I am receiving the notorious "free heap block modified after it was freed" message on data=(LPBYTE) malloc(MAX_VALUE_DATA);. This stackoverflow thread suggests that it is because I am freeing something incorrectly. And indeed if the free(data) near the bottom is uncommented, this error returns and if it is commented - goes away. How am I freeing it wrong?
// Enumerate the key values.
if (cValues)
{
printf( "\nNumber of values: %d\n", cValues);
LPBYTE data;
DWORD size;
data=(LPBYTE) malloc(MAX_VALUE_DATA);
messageProvider mp={(TCHAR*) currentRoot,NULL,NULL,NULL};
BOOL anyGoodValues=FALSE;
for (i=0, retCode=ERROR_SUCCESS; i<cValues; i++)
{
cchValue = MAX_VALUE_NAME;
achValue[0] = '\0';
ZeroMemory(data,MAX_VALUE_DATA);
//data=(LPBYTE) malloc(MAX_VALUE_DATA);
size=MAX_VALUE_DATA;
retCode = RegEnumValue(hKey, i,
achValue,
&cchValue,
NULL,
NULL,
data,
&size);
if (retCode == ERROR_SUCCESS )
{
_tprintf(TEXT("(%d) '%s'\n"), i+1, achValue);
BOOL valFound=FALSE;
if (_tcscmp(achValue,_T("ParameterMessageFile")) == 0 ){
mp.ParameterMessageFile=(TCHAR *)data;
anyGoodValues=TRUE;
valFound=TRUE;
}
if (_tcscmp(achValue,_T("CategoryMessageFile")) == 0 ){
mp.CategoryMessageFile=(TCHAR *)data;
anyGoodValues=TRUE;
valFound=TRUE;
}
if (_tcscmp(achValue,_T("EventMessageFile")) == 0 ){
mp.ParameterMessageFile=(TCHAR *)data;
anyGoodValues=TRUE;
valFound=TRUE;
}
if(!valFound){
//free(data);
}
}
}
开发者_JAVA技巧 if(anyGoodValues)
mpArray[mpIndex++]=mp;
}
You allocate once, but free inside a loop. In the future, this sort of thing will be easier to find if you always set your pointers to NULL
after calling free()
on them.
You need to move the free() outside the loop; at next iteration through the loop RegEnumValue is using data after it is freed.
Verify the "default" value for /Zp compiler option ("struct member alignment" in C/C++ Code generation) in your code and in all the the libraries.
For an explanation, see : https://stackoverflow.com/a/14444115/1997864
精彩评论