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

时间:2014-04-08 05:33:21

标签: c++ pointers

我有这段代码

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;
}

它输出六位十进制值。但是当我尝试删除它时程序崩溃了。

编辑:崩溃消息显示HEAP CORRUPTION DETECTED。

2 个答案:

答案 0 :(得分:2)

您使用unsigned char分配了一个new,因此您应该致电delete,而不是delete []。后者适用于使用new []分配的数组。

你需要

delete _hexaActual;

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

编辑:除了该错误之外,您还有一些:最重要的一个,在函数ConvertBinaryToHexaDecimal中,您传递指向单个unsigned char的指针,但你把它当成一个数组:

_outputHexaDecimal[_inputIndex/4] = ....

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

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

并且永远不会致电free

答案 1 :(得分:0)

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

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