我目前正试图删除由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无法解决我已更新我的帖子的问题 –