I am currently trying to delete the buffer returned by cocos2dx but its crashing here is my code i am getting file data from cocos2dx and then saving its pointer after that i am adding null character at the end now when i try to delete this buffer project crashes
unsigned long fSize = 0;
unsigned char* pBuff = (cocos2d::CCFileUtils::sharedFileUtils()->getFileData(szName, "r", &fSize));
int result = 0;
if(pBuff)
{
result = 1;
pBuff[fSize] = '\0';
}
delete pBuff; //crashing at this line
implementation of getFileData is
unsigned char* CCFileUtils::getFileData(const char* pszFileName, const char* pszMode,
unsigned long * pSize)
{
unsigned char * pBuffer = NULL;
CCAssert(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters.");
*pSize = 0;
do
{
// read the file from hardware
std::string fullPath = fullPathForFilename(pszFileName);
FILE *fp = fopen(fullPath.c_str(), pszMode);
CC_BREAK_IF(!fp);
fseek(fp,0,SEEK_END);
*pSize = ftell(fp);
fseek(fp,0,SEEK_SET);
pBuffer = new unsigned char[*pSize];
*pSize = fread(pBuffer,sizeof(unsigned char), *pSize,fp);
fclose(fp);
} while (0);
if (! pBuffer)
{
std::string msg = "Get data from file(";
msg.append(pszFileName).append(") failed!");
CCLOG("%s", msg.c_str());
}
return pBuffer;
}
EDIT: after changing (as suggested by David)
if(pBuff)
{
result = 1;
pBuff[fSize] = '\0';
}
delete pBuff; //crashing at this line
to
if(pBuff)
{
result = 1;
//pBuff[fSize] = '\0';
delete[] pBuff; //still crashing at this line
}
its still crashing
You are writing beyond the end of the buffer here:
pBuff[fSize] = '\0';
Your call to delete
is wrong. It needs to match the call to new
.
delete[] pBuff;
Personally I don't see why you would use raw memory allocations here. Wouldn't it be better to use a standard container, std::vector<unsigned char>
in this case. Or if for some reason you have to use raw memory allocation then at least wrap the memory up in a smart pointer.
You say that after fixing these problems, your code still fails of the delete
. That sounds like you have corrupted the heap elsewhere.