【发布时间】:2014-12-21 22:44:30
【问题描述】:
我在尝试释放动态创建的数组时收到 SIGTRAP 信号,但不知道原因。
我是这样分配数组的:
int* visited = (int*) malloc( l.nodeCount * sizeof(int));
(l.nodeCount 是一个整数。在程序的实例中我得到这个错误,它设置为 12。)
当我尝试free(visited) 时,我在调试器中收到 SIGTRAP 信号。
整个函数就是这个:
int Graph_GetSmallestPathCount(AdjacencyList l, int destination){
//One path if destination is root
if(destination == 0) return 1;
if(l.nodeCount == 0)
return 0;
Queue reading = Queue_NewQueue();
Queue storing = Queue_NewQueue();
/*Allocates visited array*/
int* visited = (int*) calloc( l.nodeCount, sizeof(int));
/*Visited array initialization*/
int i;
for(i = 0; i < l.nodeCount; i++)
visited[i] = 0;
/*Marks root node and enqueues it*/
visited[0] = 1;
Queue_Enqueue(&reading, 0);
//While there are nodes to read
while(!Queue_IsEmpty(reading))
{
//Dequeues a node
int v = Queue_Dequeue(&reading);
//Gets it's adjacency list
List* currentList = AdjacencyList_GetAdjacentNodes(l, v);
listCell* auxCell = currentList->head->next;
//While there are nodes in it's adjacency list
while(auxCell != NULL){
//Enqueues it if it has not been visited
if(visited[auxCell->data] == 0){
Queue_Enqueue(&storing, auxCell->data);
}
//Adds to the paths to that node
visited[auxCell->data] += visited[v];
auxCell = auxCell->next;
}
//When the queue ends
if(Queue_IsEmpty(reading)){
//If the destination has been reached, return
if(visited[destination] > 0){
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return visited[destination];
}
else{
//Switch queues
Queue_Destroy(&reading);
reading = storing;
storing = Queue_NewQueue();
}
}
}
//Destination has not been reached before end of algorithms. Deallocate everything and return 0
free(visited);
Queue_Destroy(&reading);
Queue_Destroy(&storing);
return 0;
}
很抱歉缺少 cmets,我是在运行中完成的,但没有放入任何内容。也很抱歉 printf 过载,我在试图查明问题时将它们放在那里。 编辑:我清理了一下。
奇怪的是,该程序适用于某些输入,而不适用于其他输入。
希望有人能帮帮我=D
【问题讨论】:
-
也许你的代码中的某些东西弄乱了堆。双重
free()也可能导致该错误。 -
auxCell->data在visited[auxCell->data] += visited[v];中的值可能等于或大于l.nodeCount? -
不能,因为它只能是图中的一个节点。我已经确定了。
-
尝试在每次为visited[n] 分配某些内容时输出[] 数字的值,以便查看是否超过了分配的内存。我猜这在某个时候会发生。如果使用 calloc,则不需要初始化数组,因为它已经将分配的内存初始化为全零。
-
你可能有一个严重的memory corruption。如果可用,请使用valgrind。
标签: c free dynamic-memory-allocation