2013-11-21 119 views
0

我正在爲使用二叉樹實現特定算法的學校分配任務。在C++中覆蓋對象

我已經算出了算法,並且我的main()在第一次迭代中正確運行,但之後seg故障正確(您應該能夠連續運行程序並模擬算法而不必運行再次,./main,因此while循環)。

我有一種感覺,它與我的第一輪創建和使用的BinaryTree *tree有關,然後在不被釋放的情況下再次使用,但是我嘗試解決此問題的嘗試毫無結果。

這裏是我主要是爲有問題的:

#include <iostream> 
using namespace std; 
#include "BinaryTree.h" 
/* Prompts user to pick an option: 
* first fit, best fit, or quit 
*/ 



int main(){ 

    bool quit; 
    int command, elements, binSize, x, totalNodes; 
    cout<<"Welcome to assignment 6!"<<endl; 


    BinaryTree *tree = new BinaryTree(); 
    //Declare new tree for use in first fit algorithm 

    while (!quit) 
    { 
     cout<<"Choose an option for the test: 1-> First fit, 2-> Best Fit, 3-> Quit"<<endl; 
     cin>>command; 

     /************** 
      First Fit 
     **************/ 

     if(command==1) 
     {  
      cout<<"First Fit!\n"; 
      cout<<"Enter number of objects: "; 
      cin>> elements; 
      cout<<"Enter capacities of bins: "; 
      cin>> binSize; 
      cout<<"\n"; 



      x=1; 
      while (elements > x) //Get next highest power of 2 
       x=x*2;  //to fill out bottom of binary tree 

      totalNodes = 2*x -1; 
      for(int i=1; i<=totalNodes; i++) 
      { 
       //cout<<"Adding node: "<<i<<endl; 
       tree->AddItem(i, -1); 
      } 

      bool done = false; 
      //elements = x; 
      int a[elements]; 
      for (int i=1; i<=elements; i++) 
      { 
       cout<<"Enter space requirement of object "<<i<<endl; 
       cin>>a[i]; 
      } 

      for (int i=1; i<=elements && !done; i++) 
      { 
       tree->Insert(a[i], binSize, elements); 
      } 

       //Loop done, seg faults happens when called again 
     } 

的BinaryTree.cpp文件是有點長,所以如果它需要我會在這裏將它們鏈接: http://pastebin.com/EtwdBp8N

任何建議或信息對不好的做法感激不盡。

+1

這樣一般的問題是沒有初始化使用,超越所分配的存儲器,或者釋放後使用。 – crashmstr

+2

使用-g編譯並使用gdb – JRG

+0

具體而言,請在您認爲是崩潰前最後一行的地方設置斷點,然後逐步瀏覽,直至看到原因。 – Marcin

回答

0

如果調試器沒有幫助,請嘗試使用valgrind http://valgrind.org/或類似的東西來運行程序。它會爲您識別許多無效的內存訪問。

2
 int a[elements]; 
     for (int i=1; i<=elements; i++) 
     { 
      cout<<"Enter space requirement of object "<<i<<endl; 
      cin>>a[i]; 
     } 

該位是錯誤的,陣列是基於零的在C/C++,環路應該是:

 for (int i=0; i<elements; i++)