gpt4 book ai didi

c++ - 插入数据后无法删除 unsigned char*

转载 作者:行者123 更新时间:2023-11-28 02:51:33 26 4
gpt4 key购买 nike

我有这个代码

unsigned char _binary[] = {'1','1','1','0','0','0','1','0',NULL};
int length = 0;
for(length=0;_binary[length];length++);
unsigned char *_hexaActual = new unsigned char;
ConvertBinaryToHexaDecimal(_binary, length, _hexaActual);
string _actual((char*)_hexaActual);
delete[] _hexaActual; // crashes here

现在 ConvertBinaryToHexaDecimal

void ConvertBinaryToHexaDecimal(const unsigned char* _inputBinary, unsigned int _intputLength, unsigned char* _outputHexaDecimal)
{
const unsigned char _hexaDecimalSymbols[16] = {'0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F'};

char* _binary =(char*) malloc(sizeof(char));
int _binaryIndex,_inputIndex;
for(_binaryIndex=0; _binaryIndex < _intputLength%4 ;_binaryIndex++) // padding extra 0's to make the length multiple of 4
_binary[_binaryIndex] = '0';
for(_inputIndex=0; _inputIndex < _intputLength ;_inputIndex++)
_binary[_inputIndex + _binaryIndex] = _inputBinary[_inputIndex];
_binary[_inputIndex + _binaryIndex] = NULL;

_intputLength = _inputIndex + _binaryIndex;
for( _inputIndex=0; _inputIndex < _intputLength; _inputIndex +=4)
{
int _binaryValue = _binary[_inputIndex] - 48;
int _binaryValue1 = _binary[_inputIndex+1] - 48;
int _binaryValue2 = _binary[_inputIndex+2] - 48;
int _binaryValue3 = _binary[_inputIndex+3] - 48;

int _hexValue = _binaryValue3 * 1;
_hexValue += _binaryValue2 * 2;
_hexValue += _binaryValue1 * 4;
_hexValue += _binaryValue * 8;

_outputHexaDecimal[_inputIndex/4] = _hexaDecimalSymbols[_hexValue];
}
_outputHexaDecimal[_inputIndex/4] = NULL;
}

它正确地输出一个十六进制值。但是当我尝试删除它时,程序崩溃了。

编辑:崩溃消息显示检测到堆损坏。

最佳答案

你用new分配了一个unsigned char,所以你应该调用delete,而不是delete [] .后者用于使用 new [] 分配的数组。

你需要

delete _hexaActual;

请注意,这种类型的手动分配和取消分配容易出错且异常不安全。您很可能可以使用标准库容器和算法来实现您的代码。

编辑:除了那个错误,你还有一些错误:最重要的一个,在函数 ConvertBinaryToHexaDecimal 中,你传递了一个指向单个 的指针unsigned char,但您将其视为数组:

_outputHexaDecimal[_inputIndex/4] = ....

接下来,你有一个内存泄漏。你在这里分配:

char* _binary =(char*) malloc(sizeof(char));

永远不要调用free

关于c++ - 插入数据后无法删除 unsigned char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22928310/

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