【问题标题】:Unhandled exception at 0x00051526 Access violation reading location 0x000000040x00051526 处的未处理异常访问冲突读取位置 0x00000004
【发布时间】:2011-06-01 04:21:48
【问题描述】:
class ByteBuffer
{
public:
    ByteBuffer(std::shared_ptr<uint8_t> buf, int len);
    explicit ByteBuffer(int len);
    virtual ~ByteBuffer(void);

    std::shared_ptr<uint8_t> getBuffer() const {return this->buffer;}
    uint16_t getLength() const {return this->length;}
private:
    std::shared_ptr<uint8_t> buffer;
    uint16_t length;
};

//-----------------------------------------------------------------------------
ByteBuffer::ByteBuffer(std::shared_ptr<uint8_t> buf, int len)
  : buffer(buf),length(len)
{ }

ByteBuffer::ByteBuffer(int len)
  : buffer(new uint8_t[len]),length(len)
{ }

ByteBuffer::~ByteBuffer(void)
{ }

//-----------------------------------------------------------------------------
class Packet
{
public:
    explicit Packet(ByteBuffer& ref);
    virtual ~Packet(void);
};

Packet::Packet(ByteBuffer& ref)
{
    // how do i intinlize it here so i can use it?
}

// i have onther method for the handling 
void HandlePacket(Packet & pack);
Handel(ByteBuffer & ref)
{
    Packet p(ref);
    HandlePacket(p); // the error happens here
}

编辑:对不起,我忘了添加发生错误的方法我很抱歉

你可以看到 2calsss,但是每次我试图在数据包中传递字节缓冲区然后使用其他方法中的数据包它给我这个错误:

AccountServer.exe 中 0x00051526 处的未处理异常:0xC0000005:访问冲突读取位置 0x00000004。

所以我的问题是我该如何解决这个问题!?

【问题讨论】:

  • 是什么让你认为shared_ptr&lt;&gt; 甚至可以在没有自定义删除器的情况下使用new[] 分配的指针?
  • @ildjarn shared_ptr 在它讨厌零时处理它,它会自动删除它,这就是我使用智能指针的原因
  • @Mixed shared_ptr 没有自定义删除器不能用于删除分配有new[] 的指针,为此使用shared_array
  • 只需将std::vector&lt;&gt; 用作您的缓冲区(而不是ByteBuffer),这正是它的用途。
  • @frag:总是未定义的行为,类型无关紧要。 new 匹配 deletenew[] 匹配 delete[]

标签: c++ memory


【解决方案1】:

您正在访问地址0x4。可能某个对象是NULL,而您尝试使用ptr[1]-&gt; 运算符来取消对它的引用。

在调试器下运行你的程序,会更清楚发生了什么。特别是它会给你一个堆栈跟踪并告诉你局部变量的状态。

正如 cmets 中所述,您不能以您期望的方式将new []shared_ptr 一起使用,因为deletedelete [] 不同。请参阅此网站,该网站在 Google 搜索中出现:http://nealabq.com/blog/2008/12/02/array_deleter/。您将需要一个执行delete [] 的客户删除程序,而不是默认的delete

【讨论】:

    猜你喜欢
    • 2011-09-28
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 2015-05-01
    • 2013-11-22
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多