函数具有损坏的返回值

时间:2010-02-09 17:12:40

标签: c++ visual-c++

我在Visual C ++ 2008中遇到过一些我以前从未见过的情况。我有一个包含4个STL对象的类(精确的列表和向量)和整数。

它有一个方法:

inline int id() { return m_id; }

此方法的返回值已损坏,我不知道为什么。

debugger screenshot http://img687.imageshack.us/img687/6728/returnvalue.png

我想相信它的堆栈粉碎,但据我所知,我没有缓冲区溢出或分配问题。


更多观察 这是让我失望的东西。调试器在提到的错误ID中打印正确的值。

  m_header = new DnsHeader();
  assert(_CrtCheckMemory());

  if (m_header->init(bytes, size))
  {
    eprintf("0The header ID is %d\n", m_header->id()); // wrong ID!!!

在m_header-> init()

 m_qdcount = ntohs(h->qdcount);
    m_ancount = ntohs(h->ancount);
    m_nscount = ntohs(h->nscount);
    m_arcount = ntohs(h->arcount);
    eprintf("The details are %d,%d,%d,%d\n", m_qdcount, m_ancount, m_nscount, m_arcount);

    // copy the flags
    // this doesn't work with a bitfield struct :(
    // memcpy(&m_flags, bytes + 2, sizeof(m_flags));
    //unpack_flags(bytes + 2); //TODO
    m_init = true;
  }
  eprintf("Assigning an id of %d\n", m_id); // Correct ID.
  return

m_header-> id()是头文件中的内联函数

inline int id() { return m_id; }

我真的不知道如何最好地发布我的代码片段,但这是我最好的镜头。如果不够,请告诉我们:

班级DnsHeaderm_header内有一个对象DnsPacket

主体:

DnsPacket *p ;
p = new DnsPacket(r);
assert (_CrtCheckMemory());
p->add_bytes(buf, r); // add bytes to a vector m_bytes inside DnsPacket
if (p->parse())
{
read_packet(sin, *p);
}

对 - >解析:

size_t size = m_bytes.size(); // m_bytes is a vector
  unsigned char *bytes = new u_char[m_bytes.size()];
  copy(m_bytes.begin(), m_bytes.end(), bytes); 

m_header = new DnsHeader();
  eprintf("m_header allocated at %x\n", m_header);
  assert(_CrtCheckMemory());
  if (m_header->init(bytes, size)) // just set the ID and a bunch of other ints here.
{
    size_t pos = DnsHeader::SIZE; // const int
    if (pos != size)
      ; // XXX perhaps generate a warning about extraneous data?

    if (ok)
      m_parsed = true;

  }
  else
  {
    m_parsed = false;
  }

  if (!ok) {
    m_parsed = false;
  }
  return m_parsed;
}

read_packet:

  DnsHeader& h = p.header();
  eprintf("The header ID is %d\n", h.id()); // ID is wrong here
...

DnsHeader构造函数:

m_id = -1;
  m_qdcount = m_ancount = m_nscount = m_arcount = 0;

  memset(&m_flags, 0, sizeof(m_flags)); // m_flags is a struct
  m_flags.rd = 1;

p.header():

return *m_header;

m_header-> init :( u_char * bytes,int size)

header_fmt *h = (header_fmt *)bytes;
m_id = ntohs(h->id);
eprintf("Assigning an id of %d/%d\n", ntohs(h->id), m_id); // ID is correct here
m_qdcount = ntohs(h->qdcount);
m_ancount = ntohs(h->ancount);
m_nscount = ntohs(h->nscount);
m_arcount = ntohs(h->arcount);

3 个答案:

答案 0 :(得分:4)

您似乎在某种程度上使用指向无效类的指针。显示的返回值是VS通常用于初始化内存的值:

2^32 - 842150451 = 0xCDCDCDCD

答案 1 :(得分:1)

  1. 您可能尚未初始化此函数所属的类。
  2. 在上下文中没有看到更多代码..可能是m_id超出了您期望的范围。

答案 2 :(得分:0)

重新安装VC ++。这解决了一切。

感谢您的时间和支持! :)欣赏它!