2013-02-25 103 views
0

我试图验证指针数组中的,所以我没有造成任何内存错误,空指针类

而且这种方法:

for(int i=0;i<array_size;i++) { 
    if (array[i]!=NULL) 
      array[i]->stuff(); 
    } 
} 

过去工作过。

现在,我必须做同样的事情,除了基于对象变量来完成所有事情。

我的新方法是:

Direct2Entity* nextset[MAX_ENTS]; // ents[MAX_ENTS] is also a Direct2Entity* array 
for(int i=0;i<MAX_ENTS;i++) { 
    nextset[i]=NULL; // note that ents[] is also flushed before this 
} 
int nextsetid=0; 
int maxn; 
bool stillnull; 
while(true) { // infinite sorting loop 
    maxn=-1; 
    stillnull=true; 
    for(int i=0;i<next_put;i++) { 
     if (ents[i]!=NULL) { 
      stillnull=false; 
      if (ents[i]->depth<0) { // make sure no infinite loops occur with negative depth 
       ents[i]->depth=0; 
      } 
      if (ents[i]->depth>maxn) { 
       nextset[nextsetid++]=ents[i]; 
       ents[i]=NULL; // make NULL to further loop 
      } 
     } 
    } 
    if (stillnull) break; 
} 
for(int i=0;i<next_put;i++) { 
    if (nextset[i]!=NULL) { 
     ents[i]=nextset[i]; // copy nextset[] to ents[] 
    } 
} 
for(int i=0;i<next_put;i++) { 
    if (ents[i]!=NULL) { 
     if (ents[i]->getroom()==current_room) { 
      ents[i]->draw(this); // ents[i] is still NULL... ? 
     } 
    } 
} 

在过去的for循环,经济需求[I]被明确检查,以确保它不会被取消引用空指针。然而C++通过它并调用函数。在各种随机地方都有各种运行时错误,但我几乎可以肯定这是来自这里的未定义行为。

+0

使用调试器浏览您的程序。它会告诉你发生错误的地方。您将能够在任何时候检查变量并将这些值与您的预期进行比较。 – 2013-02-25 04:55:57

+0

经过大约1000次f11和30个左右的汇编语言文件的处理后,我修复了重新排序算法的错误。你有没有任何提示,只保留在你的文件的步入视图..? – object 2013-02-25 05:13:46

+0

@metredigm:在调试器中查找*断点*。这允许执行直到遇到断点。一些调试器允许代码在* N *遇到断点后停止(查找触发器)。 – 2013-02-25 06:28:45

回答

0

我没有看到确定next_put值的逻辑。它有可能超过了ents []的长度?如果是这样,即使你已经正确地初始化了ents [],当你的循环离开数组的末尾,那个内存不会被初始化(至少和你所期望的一样),你的if(ents [i]!= NULL )将被传递(然后你的程序会崩溃)。