访问冲突,找不出原因

问题描述:

因此,在建设这个类:访问冲突,找不出原因

public class BitArray { 
public: 
    unsigned char* Data; 
    UInt64 BitLen; 
    UInt64 ByteLen; 

private: 
    void SetLen(UInt64 BitLen) { 
     this->BitLen = BitLen; 
     ByteLen = (BitLen + 7)/8; 
     Data = new unsigned char(ByteLen + 1); 
     Data[ByteLen] = 0; 
    } 

public: 
    BitArray(UInt64 BitLen) { 
     SetLen(BitLen); 
    } 

    BitArray(unsigned char* Data, UInt64 BitLen) { 
     SetLen(BitLen); 
     memcpy(this->Data, Data, ByteLen); 
    } 

    unsigned char GetByte(UInt64 BitStart) { 
     UInt64 ByteStart = BitStart/8; 
     unsigned char BitsLow = (BitStart - ByteStart * 8); 
     unsigned char BitsHigh = 8 - BitsLow; 

     unsigned char high = (Data[ByteStart] & ((1 << BitsHigh) - 1)) << BitsLow; 
     unsigned char low = (Data[ByteStart + 1] >> BitsHigh) & ((1 << BitsLow) - 1); 

     return high | low; 
    } 

    BitArray* SubArray(UInt64 BitStart, UInt64 BitLen) { 
     BitArray* ret = new BitArray(BitLen); 
     UInt64 rc = 0; 

     for (UInt64 i = BitStart; i < BitLen; i += 8) { 
      ret->Data[rc] = GetByte(i); 
      rc++; 
     } 

     Data[rc - 1] ^= (1 << (BitLen - ret->ByteLen * 8)) - 1; 

     return ret; 
    } 

}; 

刚写完子阵列功能,并继续测试,但我得到“访问冲突:尝试读取受保护的内存”上GetByte(i)被调用的行。我测试了一下,它似乎与数据数组或i没有任何关系,在函数的第一行放置“int derp = GetByte(0)”会产生相同的错误。

从外部调用GetByte工作正常,我不明白是怎么回事。

测试功能如下:

 unsigned char test[] = { 0, 1, 2, 3, 4, 5, 6, 7 }; 
     BitArray* juku = new BitArray(test, 64); 

     auto banana = juku->GetByte(7); //this works fine 
     auto pie = juku->SubArray(7, 8); 
+0

那么你调试了吗?你怎么调用'SubArray'?你所有变量的值是什么?你应该可以在纸上做到这一点。 – 2014-10-29 11:50:50

+0

调试吗?当我在调试模式下在VS中运行时,我得到的是访问冲突错误。 – user81993 2014-10-29 11:52:36

+1

'公共课堂'?这是一个VC++扩展吗?另外,你的main()是怎么样的?请提供[SSCCE](http://sscce.org),以便我们重现此问题。 – 2014-10-29 11:54:45

你可能要考虑创建一个字符数组,改变:

Data = new unsigned char(ByteLen + 1); 

到:

Data = new unsigned char[ByteLen + 1]; 

在前者,括号内的值是不是所需的长度,它是*Data初始化的值。如果使用65(在ASCII系统中),则第一个字符变为A

话虽如此,C++已经一个整整你似乎是在形势相当有效std::bitset。如果你的目的是要学习如何制作班,想尽一切办法自己编写。然而,如果你想让自己的生活变得简单,你可能需要考虑使用已经提供的设施,而不是自己动手。

+0

doh,多数民众赞成它! – user81993 2014-10-29 11:56:05

+2

用'std :: vector '你会好得多。这段代码非常脆弱。 – 2014-10-29 11:57:15

+0

矢量如何帮助? (也是,这个类还没有完成) – user81993 2014-10-29 11:58:02