插入数据后无法删除无符号字符*

Can't delete an unsigned char* after inserting data

本文关键字:无符号 字符 删除 数据 插入      更新时间:2023-10-16

我有这个代码

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.

你只为_hexaActual分配了一个字符,但你在ConvertBinaryToHexaDecimal中写入了许多值。您需要为要放入的字符分配足够的空间。 length/4 + 2应该这样做。

unsigned char *_hexaActual = new unsigned char[length/4 + 2];