"Stack overflow"错误。指针可能不在列表中

"Stack overflow" error. Probably pointer out of list

本文关键字:列表 指针 Stack overflow 错误      更新时间:2023-10-16

首先,我不精通编程,所以请宽容。:)
我很好奇是什么原因导致了"堆栈溢出"的错误。我正在使用Visual C++2010学习版。

struct elem
{
    BITMAP * colltile;
    elem * next;
};

/*在此处输入一些代码*/

int collision_map (unsigned int poz_x, unsigned int poz_y)
{
    elem * wsk = this->where_the_head_of_list_is;
    int x,y;
    x = poz_x%64; //coord x on tile (0-63px)
    y = poz_y%64; //coord y on tile (0-63px)
    poz_x /= 64;  //preparing poz_x and poz_y to point on a tile on a grid
    poz_y /= 64;  //integers do not have to be floored
    //for (int j=(poz_y*(this->size_x)+poz_x); j>0; j--) //normally works... but
    for (int j=0; j<1000; j++) //this version is not
    {
        if ((!(wsk = wsk->next)) ||
            ((poz_x+1) > this->size_x) ||
            ((poz_y+1) > this->size_y))
        {   //should check if there is no new pointer or just out of map
            return -1;
        }
    }
    return getpixel(wsk->colltile, x, y); 
}

j达到列表长度值时,为什么条件不起作用?

您可以/必须做的事情:

  • 添加调试输出将帮助您找到错误。在代码中添加一些std::cerr << wsk << std::endl,并检查它是否/何时变为零
  • 指针可能在elem* wsk= ...函数的开头为零。如果是这种情况,wsk->next将访问一个空指针。您必须检查指针是否有效
  • 由于类中有指针成员(如this->where_the_head_of_list_is所示),因此需要实现复制构造函数、赋值运算符和析构函数,而您可能没有实现这些。有关解释,请参见此处