2017-07-19 92 views
1

我正在Linux上使用Valgrind檢查我的內存泄漏代碼。該程序在第一個小時內運行良好,但對於有向邊的某些組合返回以下錯誤。我想知道是否需要在執行dijkstra_sp.cpp之前檢查NULL。我在下面的代碼中找到了可能是此問題中心的行。Valgrind泄漏檢測返回段錯誤

==25051== Process terminating with default action of signal 11 (SIGSEGV) 
==25051== Access not within mapped region at address 0x0 
==25051== at 0x410D79: List<DirectedEdge*>::addToList(DirectedEdge*, List<DirectedEdge*>*) (linked_list.h:76) 
==25051== by 0x410AD5: pathTo(DijkstraSPTree*, ShortestPath*, int) (dijkstra_sp.cpp:77) 
==25051== by 0x423C54: getShortestPath(EdgeWeightedDigraph*, int, int) (vehicle_searching.cpp:45) 
==25051== by 0x4187E5: netPathWeight(EdgeWeightedDigraph*, int, int, int) (vehicle_Linux.cpp:1099) 
==25051== by 0x41B8E0: Schedule(int, int, VehicleState*) (vehicle_Linux.cpp:781) 
==25051== by 0x415719: updateAndRender(VehicleState*, int) (vehicle_Linux.cpp:237) 

dijkstra_sp.cpp

struct DirectedEdge { 
    int32 from; 
    int32 to; 
    real32 weight; 
}; 

void 
pathTo(DijkstraSPTree *spTree, ShortestPath *shortestPath, int32 dest) 
{ 
    // should I assert input not null? <<<<<<<<<<<<<<<<<<<<<<<<<<< 
    List<DirectedEdge *>::traverseList(freeDirectedEdge, shortestPath->edgeList); 
    List<DirectedEdge *>::emptyList(&shortestPath->edgeList); 
    shortestPath->totalWeight = spTree->distTo[dest]; 

    // check if there IS a path to dest from the root of spTree 
    if (spTree->distTo[dest] < INFINITY) { 
     DirectedEdge *nextEdge = spTree->edgeTo[dest]; 
     if(nextEdge != 0) 
     nextEdge = spTree->edgeTo[nextEdge->from]; 
    for (DirectedEdge *nextEdge = spTree->edgeTo[dest]; 
     nextEdge != 0; 
     nextEdge = spTree->edgeTo[nextEdge->from]) { 
// FOLLOWING IS LINE 77 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 
     shortestPath->edgeList = 
     List<DirectedEdge *>::addToList(nextEdge, shortestPath->edgeList); 
    } 
    } 

linked_list.h

// item T to the list 
template<typename T> List<T> * 
List<T>::addToList(T newItem, List<T> *list) 
{ 
// Could sizeof(List<T>) being zero cause this issue? <<<<<<<<<<<<<<<<<<< 

    List<T> *resultList = (List<T> *)malloc(sizeof(List<T>)); 
FOLLOWING IS LINE 76 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< 
    resultList->item = newItem; 
    resultList->next = list; 
    return resultList; 
} 
+0

僅僅因爲你的程序在一個特定的地方崩潰了,這並不意味着這就是錯誤所在。你的bug可以在任何地方。例如,除非'List '是一個POD,如圖所示,使用'malloc()'分配它是未定義的行爲,並且是一個有保證的錯誤。 –

回答

0

你已經用完了內存。 malloc的調用發生時返回NULL(0)。當您嘗試寫入該無效指針時,您會遇到崩潰。

+0

我懷疑這個,所以我要給這個程序分配更多的內存,看看它是否崩潰。如果沒有Valgrind,對於較小的邊和頂點網絡,它工作正常。 – Far

+0

@Far對於任何嚴肅的程序,你應該檢查'NULL'的'malloc'的返回值並且正常退出並報錯。很多簡單的應用程序只是定義了一個'safe_malloc'來完成這個操作,並調用它來代替'malloc'。無論如何,使用C++你應該使用'new'。當你內存不足時它會拋出異常。 – Gene

+0

@Gene哦是的,我不知道爲什麼我忘了檢查'NULL'並使用'exit(EXIT_FAILURE)' – Far