2014-04-05 150 views
0

我目前正试图删除由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 
} 

后它仍然会崩溃,

+0

'pBuff [fSize] ='\ 0';'超出范围。我认为,返回分配的内存是不好的设计(使用std :: shared_ptr/std :: unique_ptr代替)。 'do ... while(0)'是毫无意义的(只是使用'{...}') –

+0

@DieterLücking这就是我的想法,但OP有点幸运,只是添加一个nul字符实际上会产生错误?如果是我,我可以保证它可以在测试中工作,并在交付后产生间歇性故障:) –

+0

getFileData代码来自cocos2dx游戏引擎。 删除pBuff [fSize] ='\ 0'并使用delete [] pBuff无法解决我已更新我的帖子的问题 –

回答

1

你正在编写超出缓冲区结束了:

pBuff[fSize] = '\0'; 

您拨打delete错误。它需要匹配new的呼叫。

delete[] pBuff; 

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


你说在解决这些问题后,你的代码仍然不能通过delete。这听起来像是你在其他地方损坏了堆。

+0

在您提出更改之后,它仍然崩溃 –

+0

getfiledata代码不是来自cocos2dx游戏引擎 –

+0

您可能正在损坏其他地方的堆。 –