gpt4 book ai didi

android - 删除 unsigned char* 缓冲区

转载 作者:行者123 更新时间:2023-11-28 06:58:21 25 4
gpt4 key购买 nike

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

它还在崩溃

最佳答案

你写的超出了缓冲区的末尾:

pBuff[fSize] = '\0';

您调用 delete是错的。它需要匹配对 new 的调用.

delete[] pBuff;

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


你说在解决了这些问题之后,你的代码仍然失败了 delete .这听起来像是您在其他地方损坏了堆。

关于android - 删除 unsigned char* 缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22878094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com