2012-03-14 24 views
0

我正在使用Visual Studio 2010處理C++項目,一切正常,但是當我嘗試使用xcode 4運行我的程序時,它引發了Bas_Access異常。我認爲這是因爲內存泄漏,但我不確定如何解決問題。 我有以下功能:在xcode 4中分配操作員崩潰,在MSVS2010中運行正常

// Search is my class with x and y as members and here's is a constructor 
// that I cretae in my Search.cpp class 
Search& Search::operator=(const Search& search) 
{ 
    if(this != &search) 
    { 
     x = search.x; 
     y = search.y; 
    } 
    return *this; 
} 

,這裏是我如何調用函數:

Search searchStart(0,0); 
//I created my tempSearch and initialized it with the start Search element 
Search tempSearch(searchStart); 
//bestSolution is a function that calculates the best neighbour node around the searchStart node, it returns a Search element. And stores it in a list in storage. 
Search * tempCurrent=searchStart.bestSolution(&storage); 
//Here I call my function 
tempSearch=*tempCurrent;  

我簡單地創建從現有元素的新的搜索元素,但它給了我的異常,在

x=search.x; 

它與視覺工作室完美合作。

編輯: 我剛剛添加了我的函數被調用的代碼。請原諒我無法提供完整的代碼,因爲它很長。

編輯: 這是我的bestSolution功能:

Search * searchNode::Search::bestSolution(Storage *storage) 
{ 
     //listResult is a type defined as std::list<Search *> listResult. 
    listResult::iterator it, it1; 
    listResult tempList; 
    //I've initialized the result element at (0,0) because it was creating problems 
    // if uninitialized 
     Search *result=new Search(0,0); 
    //openList is a simple list of Search elements 
    if(!storage->openList.empty()){ 
    for(it=storage->openList.begin();it!=storage->openList.end();it++) 
    { 
     tempList.push_back((*it)); 
    } 
    tempList.reverse(); 
    it1=tempList.begin(); 
    // getDistanceCost is a function that calculates the heuristic distance 
    // between two points and works fine 
    int fCost=(*it1)->getDistanceCost();  
    for(it1=storage->openList.begin();it1!=storage->openList.end();it1++) 
    { 
     if((*it1)->getDistanceCost()<=fCost){ 
     fCost=(*it1)->getDistanceCost(); 
     result=(*it1); 
    } 
    } 

    } 

    return result; 
    } 
+0

它是編譯錯誤還是運行時錯誤? – 2012-03-14 09:53:26

+1

'operator ='如何被調用?有沒有機會嘗試使用已經釋放的內存? – Asha 2012-03-14 09:54:25

+0

它確實是'x = Search.x'還是它是'x = search.x'?這是一個巨大的差異。 – bitmask 2012-03-14 09:55:18

回答

0

給你提供可以肯定的是,問題出在

Search * tempCurrent=searchStart.bestSolution(&storage); 

它必須返回一些無效的指針(也許NULL)的信息。

這種無效的指針,然後爲search參數傳遞(更精確地&search)您Search::operator=然後嘗試訪問x(以及後來的y)這個無效的指針(search.xsearch.y)的成員。

+0

好的,但是當我在Visual Studio中編譯並且它適用於我時,沒有任何問題,因爲一開始我由於這些指針而被阻塞,但現在它工作了,我認爲它可以在任何地方工作。當你用xcode或VS編譯時,有沒有區別? – Anila 2012-03-14 10:24:13

+1

@Anila:很可能你正在依賴某種未定義的行爲。你能告訴我們'bestSolution'方法的代碼(或至少是內存分配部分)嗎? – Asha 2012-03-14 10:25:38

+0

@Anila:可能是,尤其是如果你依賴未定義的行爲......這是我的猜測,你這樣做。 – 2012-03-14 10:26:17

1

我的猜測是bestSolution正在返回一個指向堆棧上分配的對象的指針。現在,當您嘗試tempSearch=*tempCurrent時,您正嘗試將值複製到導致未定義行爲的無效指針中。

編輯

縱觀bestSolution方法的實現,我認爲listResult包含Search*爲結點,你正在做的result=(*it1);。它看起來像Search對象列表中有一個指針刪除它被插入到列表中。所以你在列表中有一個入侵指針。如果您嘗試將任何內容複製到由此無效指針指向的內存中,您的程序將表現出不可預測的行爲。

+0

+1。這也是我的猜想...... – 2012-03-14 10:28:07

相關問題