删除unsigned char * buffer

时间:2014-04-05 07:46:45

标签: android c++ cocos2d-x native

我目前正在尝试删除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;

}

编辑:更改后(按照David的建议)

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
}

它还在崩溃

1 个答案:

答案 0 :(得分:1)

你正在写缓冲区的末尾:

pBuff[fSize] = '\0';

您对delete的来电是错误的。它需要匹配对new的调用。

delete[] pBuff;

我个人认为你不会在这里使用原始内存分配。在这种情况下使用标准容器std::vector<unsigned char>不是更好吗。或者,如果由于某种原因你必须使用原始内存分配,那么至少将内存包装在智能指针中。


您说在解决这些问题后,您的代码仍然无法delete。听起来你已经在其他地方破坏了堆。