什么可能导致程序崩溃?

时间:2014-08-13 06:29:13

标签: c++ function pointers

我一直致力于创建有序链表的小程序。显然,我的程序中可能存在问题(可能),因为无论何时执行此函数,程序都会以返回255崩溃。

基本上,代码的布局如下:

struct listingRec{
    int mlsNum;
    double price;
    listingNode* next
};

//the calling function
void AddListings(listingRec*& topOfList)
{

int tempmls;
char ch;

  do{

      tempmls = VerifyMLS();

      if(ValidMLS(topOfList, tempmls)){

      //(the called function)
      InsertListing(topOfList, tempmls);


      }

      else{

      cout << endl << endl
           << "*****ERROR*****"
           << endl
           << "MLS# " << tempmls << " already exists."
           << endl << endl << endl; 

      }

      cout << endl
           << "Add another listing (Y/N)? : ";
      cin  >> ch;
      ch = toupper(ch);

  }while(ch == 'Y');

}

崩溃功能,我想。

void InsertListing(listingRec*& topOfList, int theMLS)
{

    listingRec *current,
               *previous,
               *newNode;

    current = topOfList;
    previous = NULL;

    while((theMLS > current->mlsNum) && (current != NULL))
    {
        previous = current;
        current = current->next;
    }

    newNode = new (nothrow) listingRec;

    if(newNode == NULL)
    {
        cout << "Heap error - could not allocate memory" << endl;
    }

    else
    {
        if(previous == NULL)
        {
            newNode->next = current;
            topOfList = newNode;
        }
        else if(current == NULL)
        {
            previous->next = newNode;
            newNode->next = NULL;
        }
        else
        {
            previous->next = newNode;
            newNode->next = current;

        }

        newNode->mlsNum = theMLS;
        newNode->price = VerifyPrice();

    }

}

很抱歉,如果这个问题有点新手(我确定)很多人。 有趣的是我发誓这个节目昨晚正在运作,但由于某种原因,它决定今天不工作,而且我完全难过了。昨天怎么可能有用,但今天不行。

即使你没有任何线索,如果你能给我任何可能导致崩溃的提示或建议......我会非常感激..谢谢。

1 个答案:

答案 0 :(得分:2)

只是我的两分钱:

在崩溃功能中你有:

while((theMLS > current->mlsNum) && (current != NULL))

如果有current == NULL的可能性 比这一行会崩溃,因为它首先评估theMLS > current->mlsNum。 因此,如果切换语句如:

while((current != NULL) && (theMLS > current->mlsNum))

它应该有效,因为当第一个为false时,第二个语句不会被执行。

此外我注意到,您使用new创建了一个对象,但您永远不会删除它。这不应该崩溃,但会导致内存泄漏。

newNode = new (nothrow) listingRec;
相关问题