[英]deleting unsigned char* buffer
I am currently trying to delete the buffer returned by cocos2dx but its crashing here is my code i am getting file data from cocos2dx and then saving its pointer after that i am adding null character at the end now when i try to delete this buffer project crashes 我当前正在尝试删除由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
implementation of getFileData is 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;
} }
EDIT: after changing (as suggested by David) 编辑:更改后(由大卫建议)
if(pBuff)
{
result = 1;
pBuff[fSize] = '\0';
}
delete pBuff; //crashing at this line
to 至
if(pBuff)
{
result = 1;
//pBuff[fSize] = '\0';
delete[] pBuff; //still crashing at this line
}
its still crashing 它仍然崩溃
You are writing beyond the end of the buffer here: 您正在这里写缓冲区的末尾:
pBuff[fSize] = '\0';
Your call to delete
is wrong. 您的delete
呼叫是错误的。 It needs to match the call to new
. 它需要将呼叫与new
匹配。
delete[] pBuff;
Personally I don't see why you would use raw memory allocations here. 就我个人而言,我不明白为什么要在这里使用原始内存分配。 Wouldn't it be better to use a standard container, std::vector<unsigned char>
in this case. 在这种情况下,使用标准容器std::vector<unsigned char>
会更好。 Or if for some reason you have to use raw memory allocation then at least wrap the memory up in a smart pointer. 或者,如果由于某种原因必须使用原始内存分配,则至少将内存包装在智能指针中。
You say that after fixing these problems, your code still fails of the delete
. 您说解决了这些问题之后,您的代码仍然无法执行delete
。 That sounds like you have corrupted the heap elsewhere. 听起来您在其他地方损坏了堆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.