我目前正試圖刪除由cocos2dx返回的緩衝區,但其崩潰在這裏是我的代碼 我從cocos2dx獲取文件數據,然後保存它的指針後,我現在在末尾添加空字符當我嘗試刪除該緩衝區項目崩潰刪除無符號字符*緩衝區
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
實施getFileData的是
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;
}
編輯:改變(由大衛的建議)
if(pBuff)
{
result = 1;
pBuff[fSize] = '\0';
}
delete pBuff; //crashing at this line
到
if(pBuff)
{
result = 1;
//pBuff[fSize] = '\0';
delete[] pBuff; //still crashing at this line
}
後它仍然會崩潰,
'pBuff [fSize] ='\ 0';'超出範圍。我認爲,返回分配的內存是不好的設計(使用std :: shared_ptr/std :: unique_ptr代替)。 'do ... while(0)'是毫無意義的(只是使用'{...}') –
@DieterLücking這就是我的想法,但OP有點幸運,只是添加一個nul字符實際上會產生錯誤?如果是我,我可以保證它可以在測試中工作,並在交付後產生間歇性故障:) –
getFileData代碼來自cocos2dx遊戲引擎。 刪除pBuff [fSize] ='\ 0'並使用delete [] pBuff無法解決我已更新我的帖子的問題 –