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