vc 6.0 堆栈错误一例

在VC 6.0的Debug模式下调试程序,出现以下警告:

Warning: Critical memory allocation failed!
Warning: Shrinking safety pool from 512 to 512 to satisfy request of 16 bytes.
First-chance exception in FEDCP.exe (NTDLL.DLL): 0xC0000005: Access Violation.
Warning: Critical memory allocation failed!

通过跟踪,发现该错误是在调用以下代码后产生的。

 Packet *p = allocpkt();
而此包是NS2中定义的Packet,函数代码如下:

 Packet* p = Packet::alloc();
 initpkt(p);
 
 struct hdr_cmn *cmh = HDR_CMN(p);
 struct hdr_ip *iph = HDR_IP(p);
 struct hdr_spr *sph = HDR_SP(p);
 
 cmh->next_hop_ = IP_BROADCAST;
 cmh->last_hop_ = id;
 cmh->addr_type_ = NS_AF_INET;
 cmh->ptype() = PT_SPR;
 cmh->size() = sph->size() + IP_HDR_LEN;
 
 iph->saddr() = id;
 iph->sport() = RT_PORT;

 iph->daddr() = IP_BROADCAST;   //<<Address::instance().nodeshift();
 iph->dport() = RT_PORT;
 iph->ttl_ = IP_DEF_TTL;
 
 sph->seqno_ = id++; 

 TRACE("Sink(%d) send query message:%d\0", id, id);

 return p;

继续跟踪发现,是因为packet的hdrlen_值为0,也就是说:

Packet* Packet::alloc()
{
 Packet* p = free_;
 if (p != 0)
 {
  assert(p->fflag_ == FALSE);
  free_ = p->next_;
  assert(p->data_ == 0);
  
  p->uid_ = 0;
  p->time_ = 0;
 } else
 {
  TRACE("Packet alloc:%d\n", totalpacket_++);

  p = new Packet;
  p->bits_ = new unsigned char[hdrlen_];                    //此外给包头分配空间时,并没有真正分配
  if (p == 0 || p->bits_ == 0)
   abort();
 }
 init(p); // Initialize bits_[]
 (HDR_CMN(p))->next_hop_ = -2; // -1 reserved for IP_BROADCAST
 (HDR_CMN(p))->last_hop_ = -2; // -1 reserved for IP_BROADCAST
 p->fflag_ = TRUE;
 (HDR_CMN(p))->direction() = hdr_cmn::DOWN;
 /* setting all direction of pkts to be downward as default;
    until channel changes it to +1 (upward) */
 p->next_ = 0;
 return (p);
}

而在最后,我自己添加了一个release函数,如下:

void Packet::release()
{
 Packet* p = free_;

 while(p)
 {
  free_ = p->next_;

  if(p!=0 && p->bits_!=0)
  {
   delete p->bits_;                    //显然这个地方会出错。
   p->bits_ = 0;
   
   delete p->data_;
   p->data_ = 0;
  }

  p = free_;
 }
}

 

 总结一下,出现上述错误是因为有以下用法:

char * bit = new char[0];

if(bit)

     delete bit;

同时查了一下,出现堆栈错误提示的还有一种常见错误,如下:

char * bit = new char[1024];

bit[1024]='c';

delete bit;

显然数组的下标出界的,在Debug模式下会出错,但是Release好像不会。

 

你可能感兴趣的:(exception,struct,delete,query,Access,Allocation)