调用函数运行一段时间后,总是出现invalid pointer 和access violation 之类的错误,经过层层调试,我可以确定是链表操作产生的异常,但是在抛出异常之前数次执行相同的操作都没问题。高手一定要帮忙啊!程序中我调用了GetIpNetTable这个api函数来获得arp缓存表内容,MacToStr为我自己编写的一个把mac地址转成字符串的函数,经测试没有问题。//自定义链表数据结构type
  PTArpRow=^TArpRow;
  TArpRow=record
    dwIndex:DWORD;
    dwIP:DWORD;
    sMac:string;
    pNext:PTArpRow;
  end;
//创建函数
 procedure GetArpTable(var iEntries:UINT;var aTable:PTArpRow);
  var
    ipTable:MIB_IPNETTABLE;
    dwSize:DWORD;
    i:UINT;
    par:PTArpRow;
  begin
    dwSize:=0;
    aTable:=nil;
    iEntries:=0;
    if GetIpNetTable(nil,dwSize,true)=ERROR_INSUFFICIENT_BUFFER then
    begin
      if GetIpNetTable(@ipTable,dwSize,true)=NO_ERROR then
      begin
        if ipTable.dwNumEntries=0 then
          exit;
        for i:=0 to ipTable.dwNumEntries-1 do
        begin
          if ipTable.table[i].dwType=4 then
          begin
            new(par);
            iEntries:=iEntries+1;
            par.dwIndex:=ipTable.table[i].dwIndex;
            par.dwIP:=ipTable.table[i].dwAddr;
            par.sMac:=MacToStr(@(ipTable.table[i].bPhysAddr),6);
            par.pNext:=aTable;
            aTable:=par;
          end;
        end;
      end;
    end;
  end;
//清除函数
procedure CleanParMem(var pr:PTArpRow);
 var
  tmpr:PTArpRow;
 begin
  if pr=nil then
    exit;
  while pr<>nil do
  begin
    tmpr:=pr;
    pr:=tmpr.pNext;
    dispose(tmpr);
  end;
 end;
//调用函数
procedure test;
var
    tmpat:PTArpRow;
    iarn:UINT;
begin
tmpat:=nil;
while (true)do
    begin
       GetArpTable(iarn,tmpat);
       CleanParMem(tmpat);end;
end;  

解决方案 »

  1.   

    没看出来其他问题,就看到似乎有内存泄露:
    GetArpTable(iarn,tmpat); GetArpTable中
      ....
      new(par);
      ....
      par.pNext:= aTable; 
      aTable   := par;  //总是指下一个
      ....当GetArpTable返回的时候,tmpat指向最后一个结构体.....
      //释放的时候,tmpat已经指向最后一个了,表头丢失了。前面的内存全部无法被释放!!
      CleanParMem(tmpat); 解决内存泄露后再看看.
    另外,建议你用TList来实现,delphi已经封装好了,直接用吧。