gpt4 book ai didi

c - 调用 free() 函数时的 SIGTRAP

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:08 26 4
gpt4 key购买 nike

我在尝试释放动态创建的数组时收到 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;

很抱歉缺少评论,我是在运行时做的,但没有添加任何评论。也很抱歉 printf 过载,我在尝试查明问题时将它们放在那里。编辑:我稍微清理了一下。

奇怪的是程序对某些输入有效而对其他输入无效。

希望有人能帮帮我=D

最佳答案

我不能告诉你为什么你得到一个 SIGTRAP 因为你还没有发布一个最小的例子。

不过,我可以告诉你如何自己找出答案:

  1. 使您的程序可读。每行使用一条指令。 indent 工具是您的好 helper 。当然,这不会修复错误,但会让您更容易找到它。

  2. 不要那样malloc。不需要强制转换 malloc 的返回值,并且使用 calloc(l.nodeCount, sizeof (int)); 或类似的方法无论如何都更具可读性。

  3. SIGTRAP 实际上意味着您遇到了断点指令。毫无疑问,实际发生的事情是您跳转到了不是您的代码的地方,并且可能根本不是代码,但包含断点的二进制代码。为什么会这样?正常原因是内存损坏,尤其是堆栈损坏。我猜 free() 正在破坏它自己的堆栈。我猜这是因为你(在某处)写入了你分配的内存之外的内存。要对此进行测试,请使用 malloc()/calloc() 运行您的程序,紧接着是 free()exit(0) .如果可行,您就知道问题出在您正在做的事情之间。

  4. 我们无法知道您在这期间做了什么,因为您还没有(谢天谢地)发布完整的程序,但请尝试在 valgrind 下运行它。当您收到超出范围的写入时,valgrind 通常会拾取它。修复每个 valgrind 警告。这并不能保证找到解决方案,但根据我的经验,95% 的时间都会找到一个。

  5. 另请注意,return visited[destination]; 似乎在没有 free() -ing visited 的情况下退出函数,这因此是内存泄漏。

关于c - 调用 free() 函数时的 SIGTRAP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26575973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com